]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
TPac: batch holds from on-the-fly lists and bookbags
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Account.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
4 use OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
8 use OpenILS::Event;
9 use OpenSRF::Utils::JSON;
10 use Data::Dumper;
11 $Data::Dumper::Indent = 0;
12 use DateTime;
13 my $U = 'OpenILS::Application::AppUtils';
14
15 sub prepare_extended_user_info {
16     my $self = shift;
17     my @extra_flesh = @_;
18
19     $self->ctx->{user} = $self->editor->retrieve_actor_user([
20         $self->ctx->{user}->id,
21         {
22             flesh => 1,
23             flesh_fields => {
24                 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
25                 # ...
26             }
27         }
28     ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
29
30     return;
31 }
32
33 # Given an event returned by a failed attempt to create a hold, do we have
34 # permission to override?  XXX Should the permission check be scoped to a
35 # given org_unit context?
36 sub test_could_override {
37     my ($self, $event) = @_;
38
39     return 0 unless $event;
40     return 1 if $self->editor->allowed($event->{textcode} . ".override");
41     return 1 if $event->{"fail_part"} and
42         $self->editor->allowed($event->{"fail_part"} . ".override");
43     return 0;
44 }
45
46 # Find out whether we care that local copies are available
47 sub local_avail_concern {
48     my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
49
50     my $would_block = $self->ctx->{get_org_setting}->
51         ($pickup_lib, "circ.holds.hold_has_copy_at.block");
52     my $would_alert = (
53         $self->ctx->{get_org_setting}->
54             ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
55                 not $self->cgi->param("override")
56     ) unless $would_block;
57
58     if ($would_block or $would_alert) {
59         my $args = {
60             "hold_target" => $hold_target,
61             "hold_type" => $hold_type,
62             "org_unit" => $pickup_lib
63         };
64         my $local_avail = $U->simplereq(
65             "open-ils.circ",
66             "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
67         );
68         $logger->info(
69             "copy availability information for " . Dumper($args) .
70             " is " . Dumper($local_avail)
71         );
72         if (%$local_avail) { # if hash not empty
73             $self->ctx->{hold_copy_available} = $local_avail;
74             return ($would_block, $would_alert);
75         }
76     }
77
78     return (0, 0);
79 }
80
81 # context additions: 
82 #   user : au object, fleshed
83 sub load_myopac_prefs {
84     my $self = shift;
85     return $self->prepare_extended_user_info || Apache2::Const::OK;
86 }
87
88 sub load_myopac_prefs_notify {
89     my $self = shift;
90     my $e = $self->editor;
91
92     my $user_prefs = $self->fetch_optin_prefs;
93     $user_prefs = $self->update_optin_prefs($user_prefs)
94         if $self->cgi->request_method eq 'POST';
95
96     $self->ctx->{opt_in_settings} = $user_prefs; 
97
98     return Apache2::Const::OK;
99 }
100
101 sub fetch_optin_prefs {
102     my $self = shift;
103     my $e = $self->editor;
104
105     # fetch all of the opt-in settings the user has access to
106     # XXX: user's should in theory have options to opt-in to notices
107     # for remote locations, but that opens the door for a large
108     # set of generally un-used opt-ins.. needs discussion
109     my $opt_ins =  $U->simplereq(
110         'open-ils.actor',
111         'open-ils.actor.event_def.opt_in.settings.atomic',
112         $e->authtoken, $e->requestor->home_ou);
113
114     # fetch user setting values for each of the opt-in settings
115     my $user_set = $U->simplereq(
116         'open-ils.actor',
117         'open-ils.actor.patron.settings.retrieve',
118         $e->authtoken, 
119         $e->requestor->id, 
120         [map {$_->name} @$opt_ins]
121     );
122
123     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
124 }
125
126 sub update_optin_prefs {
127     my $self = shift;
128     my $user_prefs = shift;
129     my $e = $self->editor;
130     my @settings = $self->cgi->param('setting');
131     my %newsets;
132
133     # apply now-true settings
134     for my $applied (@settings) {
135         # see if setting is already applied to this user
136         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
137         $newsets{$applied} = OpenSRF::Utils::JSON->true;
138     }
139
140     # remove now-false settings
141     for my $pref (grep { $_->{value} } @$user_prefs) {
142         $newsets{$pref->{cust}->name} = undef 
143             unless grep { $_ eq $pref->{cust}->name } @settings;
144     }
145
146     $U->simplereq(
147         'open-ils.actor',
148         'open-ils.actor.patron.settings.update',
149         $e->authtoken, $e->requestor->id, \%newsets);
150
151     # update the local prefs to match reality
152     for my $pref (@$user_prefs) {
153         $pref->{value} = $newsets{$pref->{cust}->name} 
154             if exists $newsets{$pref->{cust}->name};
155     }
156
157     return $user_prefs;
158 }
159
160 sub _load_user_with_prefs {
161     my $self = shift;
162     my $stat = $self->prepare_extended_user_info('settings');
163     return $stat if $stat; # not-OK
164
165     $self->ctx->{user_setting_map} = {
166         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) } 
167             @{$self->ctx->{user}->settings}
168     };
169
170     return undef;
171 }
172
173 sub load_myopac_prefs_settings {
174     my $self = shift;
175
176     my $stat = $self->_load_user_with_prefs;
177     return $stat if $stat;
178
179     return Apache2::Const::OK
180         unless $self->cgi->request_method eq 'POST';
181
182     # some setting values from the form don't match the 
183     # required value/format for the db, so they have to be 
184     # individually translated.
185
186     my %settings;
187     my $set_map = $self->ctx->{user_setting_map};
188
189     my $key = 'opac.hits_per_page';
190     my $val = $self->cgi->param($key);
191     $settings{$key}= $val unless $$set_map{$key} eq $val;
192
193     my $now = DateTime->now->strftime('%F');
194     for $key (qw/history.circ.retention_start history.hold.retention_start/) {
195         $val = $self->cgi->param($key);
196         if($val and $val eq 'on') {
197             # Set the start time to 'now' unless a start time already exists for the user
198             $settings{$key} = $now unless $$set_map{$key};
199         } else {
200             # clear the start time if one previously existed for the user
201             $settings{$key} = undef if $$set_map{$key};
202         }
203     }
204     
205     # Send the modified settings off to be saved
206     $U->simplereq(
207         'open-ils.actor', 
208         'open-ils.actor.patron.settings.update',
209         $self->editor->authtoken, undef, \%settings);
210
211     # re-fetch user prefs 
212     $self->ctx->{updated_user_settings} = \%settings;
213     return $self->_load_user_with_prefs || Apache2::Const::OK;
214 }
215
216 sub fetch_user_holds {
217     my $self = shift;
218     my $hold_ids = shift;
219     my $ids_only = shift;
220     my $flesh = shift;
221     my $available = shift;
222     my $limit = shift;
223     my $offset = shift;
224
225     my $e = $self->editor;
226
227     if(!$hold_ids) {
228         my $circ = OpenSRF::AppSession->create('open-ils.circ');
229
230         $hold_ids = $circ->request(
231             'open-ils.circ.holds.id_list.retrieve.authoritative', 
232             $e->authtoken, 
233             $e->requestor->id
234         )->gather(1);
235         $circ->kill_me;
236     
237         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
238     }
239
240
241     return $hold_ids if $ids_only or @$hold_ids == 0;
242
243     my $args = {
244         suppress_notices => 1,
245         suppress_transits => 1,
246         suppress_mvr => 1,
247         suppress_patron_details => 1,
248         include_bre => $flesh ? 1 : 0
249     };
250
251     # ----------------------------------------------------------------
252     # Collect holds in batches of $batch_size for faster retrieval
253
254     my $batch_size = 8;
255     my $batch_idx = 0;
256     my $mk_req_batch = sub {
257         my @ses;
258         my $top_idx = $batch_idx + $batch_size;
259         while($batch_idx < $top_idx) {
260             my $hold_id = $hold_ids->[$batch_idx++];
261             last unless $hold_id;
262             my $ses = OpenSRF::AppSession->create('open-ils.circ');
263             my $req = $ses->request(
264                 'open-ils.circ.hold.details.retrieve', 
265                 $e->authtoken, $hold_id, $args);
266             push(@ses, {ses => $ses, req => $req});
267         }
268         return @ses;
269     };
270
271     my $first = 1;
272     my(@collected, @holds, @ses);
273
274     while(1) {
275         @ses = $mk_req_batch->() if $first;
276         last if $first and not @ses;
277
278         if(@collected) {
279             # If desired by the caller, filter any holds that are not available.
280             if ($available) {
281                 @collected = grep { $_->{hold}->{status} == 4 } @collected;
282             }
283             while(my $blob = pop(@collected)) {
284                 $blob->{marc_xml} = XML::LibXML->new->parse_string($blob->{hold}->{bre}->marc) if $flesh;
285                 push(@holds, $blob);
286             }
287         }
288
289         for my $req_data (@ses) {
290             push(@collected, {hold => $req_data->{req}->gather(1)});
291             $req_data->{ses}->kill_me;
292         }
293
294         @ses = $mk_req_batch->();
295         last unless @collected or @ses;
296         $first = 0;
297     }
298
299     # put the holds back into the original server sort order
300     my @sorted;
301     for my $id (@$hold_ids) {
302         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
303     }
304
305     return \@sorted;
306 }
307
308 sub handle_hold_update {
309     my $self = shift;
310     my $action = shift;
311     my $hold_ids = shift;
312     my $e = $self->editor;
313     my $url;
314
315     my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
316     @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
317
318     my $circ = OpenSRF::AppSession->create('open-ils.circ');
319
320     if($action =~ /cancel/) {
321
322         for my $hold_id (@hold_ids) {
323             my $resp = $circ->request(
324                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
325         }
326
327     } elsif ($action =~ /activate|suspend/) {
328         
329         my $vlist = [];
330         for my $hold_id (@hold_ids) {
331             my $vals = {id => $hold_id};
332
333             if($action =~ /activate/) {
334                 $vals->{frozen} = 'f';
335                 $vals->{thaw_date} = undef;
336
337             } elsif($action =~ /suspend/) {
338                 $vals->{frozen} = 't';
339                 # $vals->{thaw_date} = TODO;
340             }
341             push(@$vlist, $vals);
342         }
343
344         $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
345     } elsif ($action eq 'edit') {
346
347         my @vals = map {
348             my $val = {"id" => $_};
349             $val->{"frozen"} = $self->cgi->param("frozen");
350             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
351
352             for my $field (qw/expire_time thaw_date/) {
353                 # XXX TODO make this support other date formats, not just
354                 # MM/DD/YYYY.
355                 next unless $self->cgi->param($field) =~
356                     m:^(\d{2})/(\d{2})/(\d{4})$:;
357                 $val->{$field} = "$3-$1-$2";
358             }
359             $val;
360         } @hold_ids;
361
362         $circ->request(
363             'open-ils.circ.hold.update.batch.atomic',
364             $e->authtoken, undef, \@vals
365         )->gather(1);   # LFW XXX test for failure
366         $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
367     }
368
369     $circ->kill_me;
370     return defined($url) ? $self->generic_redirect($url) : undef;
371 }
372
373 sub load_myopac_holds {
374     my $self = shift;
375     my $e = $self->editor;
376     my $ctx = $self->ctx;
377     
378     my $limit = $self->cgi->param('limit') || 0;
379     my $offset = $self->cgi->param('offset') || 0;
380     my $action = $self->cgi->param('action') || '';
381     my $hold_id = $self->cgi->param('id');
382     my $available = int($self->cgi->param('available') || 0);
383
384     my $hold_handle_result;
385     $hold_handle_result = $self->handle_hold_update($action) if $action;
386
387     $ctx->{holds} = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
388
389     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
390 }
391
392 sub load_place_hold {
393     my $self = shift;
394     my $ctx = $self->ctx;
395     my $gos = $ctx->{get_org_setting};
396     my $e = $self->editor;
397     my $cgi = $self->cgi;
398
399     $self->ctx->{page} = 'place_hold';
400     my @targets = $cgi->param('hold_target');
401     $ctx->{hold_type} = $cgi->param('hold_type');
402     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
403
404     $logger->info("Looking at hold targets: @targets");
405
406     # if the staff client provides a patron barcode, fetch the patron
407     if (my $bc = $self->cgi->cookie("patron_barcode")) {
408         $ctx->{patron_recipient} = $U->simplereq(
409             "open-ils.actor", "open-ils.actor.user.fleshed.retrieve_by_barcode",
410             $self->editor->authtoken, $bc
411         ) or return Apache2::Const::HTTP_BAD_REQUEST;
412
413         $ctx->{default_pickup_lib} = $ctx->{patron_recipient}->home_ou;
414     }
415
416     my $request_lib = $e->requestor->ws_ou;
417     my @hold_data;
418     $ctx->{hold_data} = \@hold_data;
419
420     my $type_dispatch = {
421         T => sub {
422             my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
423             for my $id (@targets) { # force back into the correct order
424                 my ($rec) = grep {$_->id eq $id} @$recs;
425                 push(@hold_data, {target => $rec, record => $rec});
426             }
427         },
428         V => sub {
429             my $vols = $e->batch_retrieve_asset_call_number([
430                 \@targets, {
431                     "flesh" => 1,
432                     "flesh_fields" => {"acn" => ["record"]}
433                 }
434             ], {substream => 1});
435
436             for my $id (@targets) { 
437                 my ($vol) = grep {$_->id eq $id} @$vols;
438                 push(@hold_data, {target => $vol, record => $vol->record});
439             }
440         },
441         C => sub {
442             my $copies = $e->batch_retrieve_asset_copy([
443                 \@targets, {
444                     "flesh" => 2,
445                     "flesh_fields" => {
446                         "acn" => ["record"],
447                         "acp" => ["call_number"]
448                     }
449                 }
450             ], {substream => 1});
451
452             for my $id (@targets) { 
453                 my ($copy) = grep {$_->id eq $id} @$copies;
454                 push(@hold_data, {target => $copy, record => $copy->call_number->record});
455             }
456         },
457         I => sub {
458             my $isses = $e->batch_retrieve_serial_issuance([
459                 \@targets, {
460                     "flesh" => 2,
461                     "flesh_fields" => {
462                         "siss" => ["subscription"], "ssub" => ["record_entry"]
463                     }
464                 }
465             ], {substream => 1});
466
467             for my $id (@targets) { 
468                 my ($iss) = grep {$_->id eq $id} @$isses;
469                 push(@hold_data, {target => $iss, record => $iss->subscription->record_entry});
470             }
471         }
472         # ...
473
474     }->{$ctx->{hold_type}}->();
475
476     # caller sent bad target IDs or the wrong hold type
477     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
478
479     # generate the MARC xml for each record
480     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
481
482     my $pickup_lib = $cgi->param('pickup_lib');
483     # no pickup lib means no holds placement
484     return Apache2::Const::OK unless $pickup_lib;
485
486     $ctx->{hold_attempt_made} = 1;
487
488     # Give the original CGI params back to the user in case they
489     # want to try to override something.
490     $ctx->{orig_params} = $cgi->Vars;
491     delete $ctx->{orig_params}{submit};
492     delete $ctx->{orig_params}{hold_target};
493
494     my $usr = $e->requestor->id;
495
496     if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
497         # find the real hold target
498
499         $usr = $U->simplereq(
500             'open-ils.actor', 
501             "open-ils.actor.user.retrieve_id_by_barcode_or_username",
502             $e->authtoken, $cgi->param("hold_usr"));
503
504         if (defined $U->event_code($usr)) {
505             $ctx->{hold_failed} = 1;
506             $ctx->{hold_failed_event} = $usr;
507         }
508     }
509
510     # First see if we should warn/block for any holds that 
511     # might have locally available items.
512     for my $hdata (@hold_data) {
513         my ($local_block, $local_alert) = $self->local_avail_concern(
514             $hdata->{target}->id, $ctx->{hold_type}, $pickup_lib);
515     
516         if ($local_block) {
517             $hdata->{hold_failed} = 1;
518             $hdata->{hold_local_block} = 1;
519         } elsif ($local_alert) {
520             $hdata->{hold_failed} = 1;
521             $hdata->{hold_local_alert} = 1;
522         }
523     }
524
525
526     my $method = 'open-ils.circ.holds.test_and_create.batch';
527     $method .= '.override' if $cgi->param('override');
528
529     my @create_targets = map {$_->{target}->id} (grep { !$_->{hold_failed} } @hold_data);
530
531     if(@create_targets) {
532
533         my $bses = OpenSRF::AppSession->create('open-ils.circ');
534         my $breq = $bses->request( 
535             $method, 
536             $e->authtoken, 
537             {   patronid => $usr, 
538                 pickup_lib => $pickup_lib, 
539                 hold_type => $ctx->{hold_type}
540             }, 
541             \@create_targets
542         );
543
544         while (my $resp = $breq->recv) {
545
546             $resp = $resp->content;
547             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
548
549             if ($U->event_code($resp)) {
550                 $ctx->{general_hold_error} = $resp;
551                 last;
552             }
553
554             my ($hdata) = grep {$_->{target}->id eq $resp->{target}} @hold_data;
555             my $result = $resp->{result};
556
557             if ($U->event_code($result)) {
558                 # e.g. permission denied
559                 $hdata->{hold_failed} = 1;
560                 $hdata->{hold_failed_event} = $result;
561
562             } else {
563                 
564                 if(not ref $result and $result > 0) {
565                     # successul hold returns the hold ID
566
567                     $hdata->{hold_success} = $result; 
568     
569                 } else {
570                     # hold-specific failure event 
571                     $hdata->{hold_failed} = 1;
572                     $hdata->{hold_failed_event} = $result->{last_event};
573                     $hdata->{could_override} = $self->test_could_override($hdata->{hold_failed_event});
574                 }
575             }
576         }
577
578         $bses->kill_me;
579     }
580
581     # stay on the current page and display the results
582     return Apache2::Const::OK if 
583         (grep {$_->{hold_failed}} @hold_data) or $ctx->{general_hold_error};
584
585     # if successful, do some cleanup and return the 
586     # user to the requesting page.
587
588     # We also clear the patron_barcode (from the staff client)
589     # cookie at this point (otherwise it haunts the staff user
590     # later). XXX todo make sure this is best; also see that
591     # template when staff mode calls xulG.opac_hold_placed()
592     return $self->generic_redirect(
593         undef,
594         $self->cgi->cookie(
595             -name => "patron_barcode",
596             -path => "/",
597             -secure => 1,
598             -value => "",
599             -expires => "-1h"
600         )
601     );
602
603     return Apache2::Const::OK;
604 }
605
606
607 sub fetch_user_circs {
608     my $self = shift;
609     my $flesh = shift; # flesh bib data, etc.
610     my $circ_ids = shift;
611     my $limit = shift;
612     my $offset = shift;
613
614     my $e = $self->editor;
615
616     my @circ_ids;
617
618     if($circ_ids) {
619         @circ_ids = @$circ_ids;
620
621     } else {
622
623         my $circ_data = $U->simplereq(
624             'open-ils.actor', 
625             'open-ils.actor.user.checked_out',
626             $e->authtoken, 
627             $e->requestor->id
628         );
629
630         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
631
632         if($limit or $offset) {
633             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
634         }
635     }
636
637     return [] unless @circ_ids;
638
639     my $qflesh = {
640         flesh => 3,
641         flesh_fields => {
642             circ => ['target_copy'],
643             acp => ['call_number'],
644             acn => ['record']
645         }
646     };
647
648     $e->xact_begin;
649     my $circs = $e->search_action_circulation(
650         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
651
652     my @circs;
653     for my $circ (@$circs) {
654         push(@circs, {
655             circ => $circ, 
656             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
657                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
658                 undef  # pre-cat copy, use the dummy title/author instead
659         });
660     }
661     $e->xact_rollback;
662
663     # make sure the final list is in the correct order
664     my @sorted_circs;
665     for my $id (@circ_ids) {
666         push(
667             @sorted_circs,
668             (grep { $_->{circ}->id == $id } @circs)
669         );
670     }
671
672     return \@sorted_circs;
673 }
674
675
676 sub handle_circ_renew {
677     my $self = shift;
678     my $action = shift;
679     my $ctx = $self->ctx;
680
681     my @renew_ids = $self->cgi->param('circ');
682
683     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
684
685     # TODO: fire off renewal calls in batches to speed things up
686     my @responses;
687     for my $circ (@$circs) {
688
689         my $evt = $U->simplereq(
690             'open-ils.circ', 
691             'open-ils.circ.renew',
692             $self->editor->authtoken,
693             {
694                 patron_id => $self->editor->requestor->id,
695                 copy_id => $circ->{circ}->target_copy,
696                 opac_renewal => 1
697             }
698         );
699
700         # TODO return these, then insert them into the circ data 
701         # blob that is shoved into the template for each circ
702         # so the template won't have to match them
703         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
704     }
705
706     return @responses;
707 }
708
709
710 sub load_myopac_circs {
711     my $self = shift;
712     my $e = $self->editor;
713     my $ctx = $self->ctx;
714
715     $ctx->{circs} = [];
716     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
717     my $offset = $self->cgi->param('offset') || 0;
718     my $action = $self->cgi->param('action') || '';
719
720     # perform the renewal first if necessary
721     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
722
723     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
724
725     my $success_renewals = 0;
726     my $failed_renewals = 0;
727     for my $data (@{$ctx->{circs}}) {
728         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
729
730         if($resp) {
731             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
732             $data->{renewal_response} = $evt;
733             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
734             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
735         }
736     }
737
738     $ctx->{success_renewals} = $success_renewals;
739     $ctx->{failed_renewals} = $failed_renewals;
740
741     return Apache2::Const::OK;
742 }
743
744 sub load_myopac_circ_history {
745     my $self = shift;
746     my $e = $self->editor;
747     my $ctx = $self->ctx;
748     my $limit = $self->cgi->param('limit') || 15;
749     my $offset = $self->cgi->param('offset') || 0;
750
751     $ctx->{circ_history_limit} = $limit;
752     $ctx->{circ_history_offset} = $offset;
753
754     my $circ_ids = $e->json_query({
755         select => {
756             au => [{
757                 column => 'id', 
758                 transform => 'action.usr_visible_circs', 
759                 result_field => 'id'
760             }]
761         },
762         from => 'au',
763         where => {id => $e->requestor->id}, 
764         limit => $limit,
765         offset => $offset
766     });
767
768     $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
769     return Apache2::Const::OK;
770 }
771
772 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
773 sub load_myopac_hold_history {
774     my $self = shift;
775     my $e = $self->editor;
776     my $ctx = $self->ctx;
777     my $limit = $self->cgi->param('limit') || 15;
778     my $offset = $self->cgi->param('offset') || 0;
779     $ctx->{hold_history_limit} = $limit;
780     $ctx->{hold_history_offset} = $offset;
781
782     my $hold_ids = $e->json_query({
783         select => {
784             au => [{
785                 column => 'id', 
786                 transform => 'action.usr_visible_holds', 
787                 result_field => 'id'
788             }]
789         },
790         from => 'au',
791         where => {id => $e->requestor->id}, 
792         limit => $limit,
793         offset => $offset
794     });
795
796     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0);
797     return Apache2::Const::OK;
798 }
799
800 sub load_myopac_payment_form {
801     my $self = shift;
802     my $r;
803
804     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
805     $r = $self->prepare_extended_user_info and return $r;
806
807     return Apache2::Const::OK;
808 }
809
810 # TODO: add other filter options as params/configs/etc.
811 sub load_myopac_payments {
812     my $self = shift;
813     my $limit = $self->cgi->param('limit') || 20;
814     my $offset = $self->cgi->param('offset') || 0;
815     my $e = $self->editor;
816
817     $self->ctx->{payment_history_limit} = $limit;
818     $self->ctx->{payment_history_offset} = $offset;
819
820     my $args = {};
821     $args->{limit} = $limit if $limit;
822     $args->{offset} = $offset if $offset;
823
824     if (my $max_age = $self->ctx->{get_org_setting}->(
825         $e->requestor->home_ou, "opac.payment_history_age_limit"
826     )) {
827         my $min_ts = DateTime->now(
828             "time_zone" => DateTime::TimeZone->new("name" => "local"),
829         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
830         
831         $logger->info("XXX min_ts: $min_ts");
832         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
833     }
834
835     $self->ctx->{payments} = $U->simplereq(
836         'open-ils.actor',
837         'open-ils.actor.user.payments.retrieve.atomic',
838         $e->authtoken, $e->requestor->id, $args);
839
840     return Apache2::Const::OK;
841 }
842
843 sub load_myopac_pay {
844     my $self = shift;
845     my $r;
846
847     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and
848         return $r;
849
850     # balance_owed is computed specifically from the fines we're trying
851     # to pay in this case.
852     if ($self->ctx->{fines}->{balance_owed} <= 0) {
853         $self->apache->log->info(
854             sprintf("Can't pay non-positive balance. xacts selected: (%s)",
855                 join(", ", map(int, $self->cgi->param("xact"), $self->cgi->param('xact_misc'))))
856         );
857         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
858     }
859
860     my $cc_args = {"where_process" => 1};
861
862     $cc_args->{$_} = $self->cgi->param($_) for (qw/
863         number cvv2 expire_year expire_month billing_first
864         billing_last billing_address billing_city billing_state
865         billing_zip
866     /);
867
868     my $args = {
869         "cc_args" => $cc_args,
870         "userid" => $self->ctx->{user}->id,
871         "payment_type" => "credit_card_payment",
872         "payments" => $self->prepare_fines_for_payment   # should be safe after self->prepare_fines
873     };
874
875     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
876         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
877     );
878
879     $self->ctx->{"payment_response"} = $resp;
880
881     unless ($resp->{"textcode"}) {
882         $self->ctx->{printable_receipt} = $U->simplereq(
883            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
884            $self->editor->authtoken, $resp->{payments}
885         );
886     }
887
888     return Apache2::Const::OK;
889 }
890
891 sub load_myopac_receipt_print {
892     my $self = shift;
893
894     $self->ctx->{printable_receipt} = $U->simplereq(
895        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
896        $self->editor->authtoken, [$self->cgi->param("payment")]
897     );
898
899     return Apache2::Const::OK;
900 }
901
902 sub load_myopac_receipt_email {
903     my $self = shift;
904
905     # The following ML method doesn't actually check whether the user in
906     # question has an email address, so we do.
907     if ($self->ctx->{user}->email) {
908         $self->ctx->{email_receipt_result} = $U->simplereq(
909            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
910            $self->editor->authtoken, [$self->cgi->param("payment")]
911         );
912     } else {
913         $self->ctx->{email_receipt_result} =
914             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
915     }
916
917     return Apache2::Const::OK;
918 }
919
920 sub prepare_fines {
921     my ($self, $limit, $offset, $id_list) = @_;
922
923     # XXX TODO: check for failure after various network calls
924
925     # It may be unclear, but this result structure lumps circulation and
926     # reservation fines together, and keeps grocery fines separate.
927     $self->ctx->{"fines"} = {
928         "circulation" => [],
929         "grocery" => [],
930         "total_paid" => 0,
931         "total_owed" => 0,
932         "balance_owed" => 0
933     };
934
935     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
936
937     # TODO: This should really be a ML call, but the existing calls 
938     # return an excessive amount of data and don't offer streaming
939
940     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
941
942     my $req = $cstore->request(
943         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
944         {
945             usr => $self->editor->requestor->id,
946             balance_owed => {'!=' => 0},
947             ($id_list && @$id_list ? ("id" => $id_list) : ()),
948         },
949         {
950             flesh => 4,
951             flesh_fields => {
952                 mobts => [qw/grocery circulation reservation/],
953                 bresv => ['target_resource_type'],
954                 brt => ['record'],
955                 mg => ['billings'],
956                 mb => ['btype'],
957                 circ => ['target_copy'],
958                 acp => ['call_number'],
959                 acn => ['record']
960             },
961             order_by => { mobts => 'xact_start' },
962             %paging
963         }
964     );
965
966     my @total_keys = qw/total_paid total_owed balance_owed/;
967     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
968
969     while(my $resp = $req->recv) {
970         my $mobts = $resp->content;
971         my $circ = $mobts->circulation;
972
973         my $last_billing;
974         if($mobts->grocery) {
975             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
976             $last_billing = pop(@billings);
977         }
978
979         # XXX TODO confirm that the following, and the later division by 100.0
980         # to get a floating point representation once again, is sufficiently
981         # "money-safe" math.
982         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
983
984         my $marc_xml = undef;
985         if ($mobts->xact_type eq 'reservation' and
986             $mobts->reservation->target_resource_type->record) {
987             $marc_xml = XML::LibXML->new->parse_string(
988                 $mobts->reservation->target_resource_type->record->marc
989             );
990         } elsif ($mobts->xact_type eq 'circulation' and
991             $circ->target_copy->call_number->id != -1) {
992             $marc_xml = XML::LibXML->new->parse_string(
993                 $circ->target_copy->call_number->record->marc
994             );
995         }
996
997         push(
998             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
999             {
1000                 xact => $mobts,
1001                 last_grocery_billing => $last_billing,
1002                 marc_xml => $marc_xml
1003             } 
1004         );
1005     }
1006
1007     $cstore->kill_me;
1008
1009     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1010     return;
1011 }
1012
1013 sub prepare_fines_for_payment {
1014     # This assumes $self->prepare_fines has already been run
1015     my ($self) = @_;
1016
1017     my @results = ();
1018     if ($self->ctx->{fines}) {
1019         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1020             @{$self->ctx->{fines}->{circulation}},
1021             @{$self->ctx->{fines}->{grocery}}
1022         );
1023     }
1024
1025     return \@results;
1026 }
1027
1028 sub load_myopac_main {
1029     my $self = shift;
1030     my $limit = $self->cgi->param('limit') || 0;
1031     my $offset = $self->cgi->param('offset') || 0;
1032
1033     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1034 }
1035
1036 sub load_myopac_update_email {
1037     my $self = shift;
1038     my $e = $self->editor;
1039     my $ctx = $self->ctx;
1040     my $email = $self->cgi->param('email') || '';
1041
1042     # needed for most up-to-date email address
1043     if (my $r = $self->prepare_extended_user_info) { return $r };
1044
1045     return Apache2::Const::OK 
1046         unless $self->cgi->request_method eq 'POST';
1047
1048     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1049         $ctx->{invalid_email} = $email;
1050         return Apache2::Const::OK;
1051     }
1052
1053     my $stat = $U->simplereq(
1054         'open-ils.actor', 
1055         'open-ils.actor.user.email.update', 
1056         $e->authtoken, $email);
1057
1058     unless ($self->cgi->param("redirect_to")) {
1059         my $url = $self->apache->unparsed_uri;
1060         $url =~ s/update_email/prefs/;
1061
1062         return $self->generic_redirect($url);
1063     }
1064
1065     return $self->generic_redirect;
1066 }
1067
1068 sub load_myopac_update_username {
1069     my $self = shift;
1070     my $e = $self->editor;
1071     my $ctx = $self->ctx;
1072     my $username = $self->cgi->param('username') || '';
1073
1074     return Apache2::Const::OK 
1075         unless $self->cgi->request_method eq 'POST';
1076
1077     unless($username and $username !~ /\s/) { # any other username restrictions?
1078         $ctx->{invalid_username} = $username;
1079         return Apache2::Const::OK;
1080     }
1081
1082     if($username ne $e->requestor->usrname) {
1083
1084         my $evt = $U->simplereq(
1085             'open-ils.actor', 
1086             'open-ils.actor.user.username.update', 
1087             $e->authtoken, $username);
1088
1089         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1090             $ctx->{username_exists} = $username;
1091             return Apache2::Const::OK;
1092         }
1093     }
1094
1095     my $url = $self->apache->unparsed_uri;
1096     $url =~ s/update_username/prefs/;
1097
1098     return $self->generic_redirect($url);
1099 }
1100
1101 sub load_myopac_update_password {
1102     my $self = shift;
1103     my $e = $self->editor;
1104     my $ctx = $self->ctx;
1105
1106     return Apache2::Const::OK 
1107         unless $self->cgi->request_method eq 'POST';
1108
1109     my $current_pw = $self->cgi->param('current_pw') || '';
1110     my $new_pw = $self->cgi->param('new_pw') || '';
1111     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1112
1113     unless($new_pw eq $new_pw2) {
1114         $ctx->{password_nomatch} = 1;
1115         return Apache2::Const::OK;
1116     }
1117
1118     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1119
1120     if($pw_regex and $new_pw !~ /$pw_regex/) {
1121         $ctx->{password_invalid} = 1;
1122         return Apache2::Const::OK;
1123     }
1124
1125     my $evt = $U->simplereq(
1126         'open-ils.actor', 
1127         'open-ils.actor.user.password.update', 
1128         $e->authtoken, $new_pw, $current_pw);
1129
1130
1131     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1132         $ctx->{password_incorrect} = 1;
1133         return Apache2::Const::OK;
1134     }
1135
1136     my $url = $self->apache->unparsed_uri;
1137     $url =~ s/update_password/prefs/;
1138
1139     return $self->generic_redirect($url);
1140 }
1141
1142 sub load_myopac_bookbags {
1143     my $self = shift;
1144     my $e = $self->editor;
1145     my $ctx = $self->ctx;
1146
1147     $e->xact_begin; # replication...
1148
1149     my $rv = $self->load_mylist;
1150     unless($rv eq Apache2::Const::OK) {
1151         $e->rollback;
1152         return $rv;
1153     }
1154
1155     my $args = {
1156         order_by => {cbreb => 'name'},
1157         limit => $self->cgi->param('limit') || 10,
1158         offset => $self->cgi->param('offset') || 0
1159     };
1160
1161     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1162         [
1163             {owner => $self->editor->requestor->id, btype => 'bookbag'},
1164             {"flesh" => 1, "flesh_fields" => {"cbreb" => ["items"]}, %$args}
1165         ], 
1166         {substream => 1}
1167     );
1168
1169     if(!$ctx->{bookbags}) {
1170         $e->rollback;
1171         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1172     }
1173     
1174     # get unique record IDs
1175     my %rec_ids = ();
1176     foreach my $bbag (@{$ctx->{bookbags}}) {
1177         foreach my $rec_id (
1178             map { $_->target_biblio_record_entry } @{$bbag->items}
1179         ) {
1180             $rec_ids{$rec_id} = 1;
1181         }
1182     }
1183
1184     $ctx->{bookbags_marc_xml} = $self->fetch_marc_xml_by_id([keys %rec_ids]);
1185
1186     $e->rollback;
1187     return Apache2::Const::OK;
1188 }
1189
1190
1191 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1192 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1193 sub load_myopac_bookbag_update {
1194     my ($self, $action, $list_id, @hold_recs) = @_;
1195     my $e = $self->editor;
1196     my $cgi = $self->cgi;
1197
1198     $action ||= $cgi->param('action');
1199     $list_id ||= $cgi->param('list');
1200
1201     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1202     my @selected_item = $cgi->param('selected_item');
1203     my $shared = $cgi->param('shared');
1204     my $name = $cgi->param('name');
1205     my $success = 0;
1206     my $list;
1207
1208     if($action eq 'create') {
1209         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1210         $list->name($name);
1211         $list->owner($e->requestor->id);
1212         $list->btype('bookbag');
1213         $list->pub($shared ? 't' : 'f');
1214         $success = $U->simplereq('open-ils.actor', 
1215             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1216
1217     } elsif($action eq 'place_hold') {
1218
1219         # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1220         unless (@hold_recs) {
1221             if (@selected_item) {
1222                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1223                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1224             }
1225         }
1226                 
1227         return Apache2::Const::OK unless @hold_recs;
1228         $logger->info("placing holds from list page on: @hold_recs");
1229
1230         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1231         $url .= ';hold_target=' . $_ for @hold_recs;
1232         return $self->generic_redirect($url);
1233
1234     } else {
1235
1236         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1237
1238         return Apache2::Const::HTTP_BAD_REQUEST unless 
1239             $list and $list->owner == $e->requestor->id;
1240     }
1241
1242     if($action eq 'delete') {
1243         $success = $U->simplereq('open-ils.actor', 
1244             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1245
1246     } elsif($action eq 'show') {
1247         unless($U->is_true($list->pub)) {
1248             $list->pub('t');
1249             $success = $U->simplereq('open-ils.actor', 
1250                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1251         }
1252
1253     } elsif($action eq 'hide') {
1254         if($U->is_true($list->pub)) {
1255             $list->pub('f');
1256             $success = $U->simplereq('open-ils.actor', 
1257                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1258         }
1259
1260     } elsif($action eq 'rename') {
1261         if($name) {
1262             $list->name($name);
1263             $success = $U->simplereq('open-ils.actor', 
1264                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1265         }
1266
1267     } elsif($action eq 'add_rec') {
1268         foreach my $add_rec (@add_rec) {
1269             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1270             $item->bucket($list_id);
1271             $item->target_biblio_record_entry($add_rec);
1272             $success = $U->simplereq('open-ils.actor', 
1273                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1274             last unless $success;
1275         }
1276
1277     } elsif($action eq 'del_item') {
1278         foreach (@selected_item) {
1279             $success = $U->simplereq(
1280                 'open-ils.actor',
1281                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1282             );
1283             last unless $success;
1284         }
1285     }
1286
1287     return $self->generic_redirect if $success;
1288
1289     $self->ctx->{bucket_action} = $action;
1290     $self->ctx->{bucket_action_failed} = 1;
1291     return Apache2::Const::OK;
1292 }
1293
1294 1