]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
UI cleanup for batch-holds from lists
[working/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     return $self->post_hold_redirect unless @targets;
405
406     $logger->info("Looking at hold targets: @targets");
407
408     # if the staff client provides a patron barcode, fetch the patron
409     if (my $bc = $self->cgi->cookie("patron_barcode")) {
410         $ctx->{patron_recipient} = $U->simplereq(
411             "open-ils.actor", "open-ils.actor.user.fleshed.retrieve_by_barcode",
412             $self->editor->authtoken, $bc
413         ) or return Apache2::Const::HTTP_BAD_REQUEST;
414
415         $ctx->{default_pickup_lib} = $ctx->{patron_recipient}->home_ou;
416     }
417
418     my $request_lib = $e->requestor->ws_ou;
419     my @hold_data;
420     $ctx->{hold_data} = \@hold_data;
421
422     my $type_dispatch = {
423         T => sub {
424             my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
425             for my $id (@targets) { # force back into the correct order
426                 my ($rec) = grep {$_->id eq $id} @$recs;
427                 push(@hold_data, {target => $rec, record => $rec});
428             }
429         },
430         V => sub {
431             my $vols = $e->batch_retrieve_asset_call_number([
432                 \@targets, {
433                     "flesh" => 1,
434                     "flesh_fields" => {"acn" => ["record"]}
435                 }
436             ], {substream => 1});
437
438             for my $id (@targets) { 
439                 my ($vol) = grep {$_->id eq $id} @$vols;
440                 push(@hold_data, {target => $vol, record => $vol->record});
441             }
442         },
443         C => sub {
444             my $copies = $e->batch_retrieve_asset_copy([
445                 \@targets, {
446                     "flesh" => 2,
447                     "flesh_fields" => {
448                         "acn" => ["record"],
449                         "acp" => ["call_number"]
450                     }
451                 }
452             ], {substream => 1});
453
454             for my $id (@targets) { 
455                 my ($copy) = grep {$_->id eq $id} @$copies;
456                 push(@hold_data, {target => $copy, record => $copy->call_number->record});
457             }
458         },
459         I => sub {
460             my $isses = $e->batch_retrieve_serial_issuance([
461                 \@targets, {
462                     "flesh" => 2,
463                     "flesh_fields" => {
464                         "siss" => ["subscription"], "ssub" => ["record_entry"]
465                     }
466                 }
467             ], {substream => 1});
468
469             for my $id (@targets) { 
470                 my ($iss) = grep {$_->id eq $id} @$isses;
471                 push(@hold_data, {target => $iss, record => $iss->subscription->record_entry});
472             }
473         }
474         # ...
475
476     }->{$ctx->{hold_type}}->();
477
478     # caller sent bad target IDs or the wrong hold type
479     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
480
481     # generate the MARC xml for each record
482     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
483
484     my $pickup_lib = $cgi->param('pickup_lib');
485     # no pickup lib means no holds placement
486     return Apache2::Const::OK unless $pickup_lib;
487
488     $ctx->{hold_attempt_made} = 1;
489
490     # Give the original CGI params back to the user in case they
491     # want to try to override something.
492     $ctx->{orig_params} = $cgi->Vars;
493     delete $ctx->{orig_params}{submit};
494     delete $ctx->{orig_params}{hold_target};
495
496     my $usr = $e->requestor->id;
497
498     if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
499         # find the real hold target
500
501         $usr = $U->simplereq(
502             'open-ils.actor', 
503             "open-ils.actor.user.retrieve_id_by_barcode_or_username",
504             $e->authtoken, $cgi->param("hold_usr"));
505
506         if (defined $U->event_code($usr)) {
507             $ctx->{hold_failed} = 1;
508             $ctx->{hold_failed_event} = $usr;
509         }
510     }
511
512     # First see if we should warn/block for any holds that 
513     # might have locally available items.
514     for my $hdata (@hold_data) {
515         my ($local_block, $local_alert) = $self->local_avail_concern(
516             $hdata->{target}->id, $ctx->{hold_type}, $pickup_lib);
517     
518         if ($local_block) {
519             $hdata->{hold_failed} = 1;
520             $hdata->{hold_local_block} = 1;
521         } elsif ($local_alert) {
522             $hdata->{hold_failed} = 1;
523             $hdata->{hold_local_alert} = 1;
524         }
525     }
526
527
528     my $method = 'open-ils.circ.holds.test_and_create.batch';
529     $method .= '.override' if $cgi->param('override');
530
531     my @create_targets = map {$_->{target}->id} (grep { !$_->{hold_failed} } @hold_data);
532
533     if(@create_targets) {
534
535         my $bses = OpenSRF::AppSession->create('open-ils.circ');
536         my $breq = $bses->request( 
537             $method, 
538             $e->authtoken, 
539             {   patronid => $usr, 
540                 pickup_lib => $pickup_lib, 
541                 hold_type => $ctx->{hold_type}
542             }, 
543             \@create_targets
544         );
545
546         while (my $resp = $breq->recv) {
547
548             $resp = $resp->content;
549             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
550
551             if ($U->event_code($resp)) {
552                 $ctx->{general_hold_error} = $resp;
553                 last;
554             }
555
556             my ($hdata) = grep {$_->{target}->id eq $resp->{target}} @hold_data;
557             my $result = $resp->{result};
558
559             if ($U->event_code($result)) {
560                 # e.g. permission denied
561                 $hdata->{hold_failed} = 1;
562                 $hdata->{hold_failed_event} = $result;
563
564             } else {
565                 
566                 if(not ref $result and $result > 0) {
567                     # successul hold returns the hold ID
568
569                     $hdata->{hold_success} = $result; 
570     
571                 } else {
572                     # hold-specific failure event 
573                     $hdata->{hold_failed} = 1;
574                     $hdata->{hold_failed_event} = $result->{last_event};
575                     $hdata->{could_override} = $self->test_could_override($hdata->{hold_failed_event});
576                 }
577             }
578         }
579
580         $bses->kill_me;
581     }
582
583     # stay on the current page and display the results
584     return Apache2::Const::OK if 
585         (grep {$_->{hold_failed}} @hold_data) or $ctx->{general_hold_error};
586
587     # if successful, do some cleanup and return the 
588     # user to the requesting page.
589
590     return $self->post_hold_redirect;
591 }
592
593 sub post_hold_redirect {
594     my $self = shift;
595
596     # We also clear the patron_barcode (from the staff client)
597     # cookie at this point (otherwise it haunts the staff user
598     # later). XXX todo make sure this is best; also see that
599     # template when staff mode calls xulG.opac_hold_placed()
600     return $self->generic_redirect(
601         undef,
602         $self->cgi->cookie(
603             -name => "patron_barcode",
604             -path => "/",
605             -secure => 1,
606             -value => "",
607             -expires => "-1h"
608         )
609     );
610 }
611
612
613 sub fetch_user_circs {
614     my $self = shift;
615     my $flesh = shift; # flesh bib data, etc.
616     my $circ_ids = shift;
617     my $limit = shift;
618     my $offset = shift;
619
620     my $e = $self->editor;
621
622     my @circ_ids;
623
624     if($circ_ids) {
625         @circ_ids = @$circ_ids;
626
627     } else {
628
629         my $circ_data = $U->simplereq(
630             'open-ils.actor', 
631             'open-ils.actor.user.checked_out',
632             $e->authtoken, 
633             $e->requestor->id
634         );
635
636         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
637
638         if($limit or $offset) {
639             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
640         }
641     }
642
643     return [] unless @circ_ids;
644
645     my $qflesh = {
646         flesh => 3,
647         flesh_fields => {
648             circ => ['target_copy'],
649             acp => ['call_number'],
650             acn => ['record']
651         }
652     };
653
654     $e->xact_begin;
655     my $circs = $e->search_action_circulation(
656         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
657
658     my @circs;
659     for my $circ (@$circs) {
660         push(@circs, {
661             circ => $circ, 
662             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
663                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
664                 undef  # pre-cat copy, use the dummy title/author instead
665         });
666     }
667     $e->xact_rollback;
668
669     # make sure the final list is in the correct order
670     my @sorted_circs;
671     for my $id (@circ_ids) {
672         push(
673             @sorted_circs,
674             (grep { $_->{circ}->id == $id } @circs)
675         );
676     }
677
678     return \@sorted_circs;
679 }
680
681
682 sub handle_circ_renew {
683     my $self = shift;
684     my $action = shift;
685     my $ctx = $self->ctx;
686
687     my @renew_ids = $self->cgi->param('circ');
688
689     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
690
691     # TODO: fire off renewal calls in batches to speed things up
692     my @responses;
693     for my $circ (@$circs) {
694
695         my $evt = $U->simplereq(
696             'open-ils.circ', 
697             'open-ils.circ.renew',
698             $self->editor->authtoken,
699             {
700                 patron_id => $self->editor->requestor->id,
701                 copy_id => $circ->{circ}->target_copy,
702                 opac_renewal => 1
703             }
704         );
705
706         # TODO return these, then insert them into the circ data 
707         # blob that is shoved into the template for each circ
708         # so the template won't have to match them
709         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
710     }
711
712     return @responses;
713 }
714
715
716 sub load_myopac_circs {
717     my $self = shift;
718     my $e = $self->editor;
719     my $ctx = $self->ctx;
720
721     $ctx->{circs} = [];
722     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
723     my $offset = $self->cgi->param('offset') || 0;
724     my $action = $self->cgi->param('action') || '';
725
726     # perform the renewal first if necessary
727     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
728
729     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
730
731     my $success_renewals = 0;
732     my $failed_renewals = 0;
733     for my $data (@{$ctx->{circs}}) {
734         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
735
736         if($resp) {
737             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
738             $data->{renewal_response} = $evt;
739             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
740             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
741         }
742     }
743
744     $ctx->{success_renewals} = $success_renewals;
745     $ctx->{failed_renewals} = $failed_renewals;
746
747     return Apache2::Const::OK;
748 }
749
750 sub load_myopac_circ_history {
751     my $self = shift;
752     my $e = $self->editor;
753     my $ctx = $self->ctx;
754     my $limit = $self->cgi->param('limit') || 15;
755     my $offset = $self->cgi->param('offset') || 0;
756
757     $ctx->{circ_history_limit} = $limit;
758     $ctx->{circ_history_offset} = $offset;
759
760     my $circ_ids = $e->json_query({
761         select => {
762             au => [{
763                 column => 'id', 
764                 transform => 'action.usr_visible_circs', 
765                 result_field => 'id'
766             }]
767         },
768         from => 'au',
769         where => {id => $e->requestor->id}, 
770         limit => $limit,
771         offset => $offset
772     });
773
774     $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
775     return Apache2::Const::OK;
776 }
777
778 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
779 sub load_myopac_hold_history {
780     my $self = shift;
781     my $e = $self->editor;
782     my $ctx = $self->ctx;
783     my $limit = $self->cgi->param('limit') || 15;
784     my $offset = $self->cgi->param('offset') || 0;
785     $ctx->{hold_history_limit} = $limit;
786     $ctx->{hold_history_offset} = $offset;
787
788     my $hold_ids = $e->json_query({
789         select => {
790             au => [{
791                 column => 'id', 
792                 transform => 'action.usr_visible_holds', 
793                 result_field => 'id'
794             }]
795         },
796         from => 'au',
797         where => {id => $e->requestor->id}, 
798         limit => $limit,
799         offset => $offset
800     });
801
802     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0);
803     return Apache2::Const::OK;
804 }
805
806 sub load_myopac_payment_form {
807     my $self = shift;
808     my $r;
809
810     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
811     $r = $self->prepare_extended_user_info and return $r;
812
813     return Apache2::Const::OK;
814 }
815
816 # TODO: add other filter options as params/configs/etc.
817 sub load_myopac_payments {
818     my $self = shift;
819     my $limit = $self->cgi->param('limit') || 20;
820     my $offset = $self->cgi->param('offset') || 0;
821     my $e = $self->editor;
822
823     $self->ctx->{payment_history_limit} = $limit;
824     $self->ctx->{payment_history_offset} = $offset;
825
826     my $args = {};
827     $args->{limit} = $limit if $limit;
828     $args->{offset} = $offset if $offset;
829
830     if (my $max_age = $self->ctx->{get_org_setting}->(
831         $e->requestor->home_ou, "opac.payment_history_age_limit"
832     )) {
833         my $min_ts = DateTime->now(
834             "time_zone" => DateTime::TimeZone->new("name" => "local"),
835         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
836         
837         $logger->info("XXX min_ts: $min_ts");
838         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
839     }
840
841     $self->ctx->{payments} = $U->simplereq(
842         'open-ils.actor',
843         'open-ils.actor.user.payments.retrieve.atomic',
844         $e->authtoken, $e->requestor->id, $args);
845
846     return Apache2::Const::OK;
847 }
848
849 sub load_myopac_pay {
850     my $self = shift;
851     my $r;
852
853     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and
854         return $r;
855
856     # balance_owed is computed specifically from the fines we're trying
857     # to pay in this case.
858     if ($self->ctx->{fines}->{balance_owed} <= 0) {
859         $self->apache->log->info(
860             sprintf("Can't pay non-positive balance. xacts selected: (%s)",
861                 join(", ", map(int, $self->cgi->param("xact"), $self->cgi->param('xact_misc'))))
862         );
863         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
864     }
865
866     my $cc_args = {"where_process" => 1};
867
868     $cc_args->{$_} = $self->cgi->param($_) for (qw/
869         number cvv2 expire_year expire_month billing_first
870         billing_last billing_address billing_city billing_state
871         billing_zip
872     /);
873
874     my $args = {
875         "cc_args" => $cc_args,
876         "userid" => $self->ctx->{user}->id,
877         "payment_type" => "credit_card_payment",
878         "payments" => $self->prepare_fines_for_payment   # should be safe after self->prepare_fines
879     };
880
881     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
882         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
883     );
884
885     $self->ctx->{"payment_response"} = $resp;
886
887     unless ($resp->{"textcode"}) {
888         $self->ctx->{printable_receipt} = $U->simplereq(
889            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
890            $self->editor->authtoken, $resp->{payments}
891         );
892     }
893
894     return Apache2::Const::OK;
895 }
896
897 sub load_myopac_receipt_print {
898     my $self = shift;
899
900     $self->ctx->{printable_receipt} = $U->simplereq(
901        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
902        $self->editor->authtoken, [$self->cgi->param("payment")]
903     );
904
905     return Apache2::Const::OK;
906 }
907
908 sub load_myopac_receipt_email {
909     my $self = shift;
910
911     # The following ML method doesn't actually check whether the user in
912     # question has an email address, so we do.
913     if ($self->ctx->{user}->email) {
914         $self->ctx->{email_receipt_result} = $U->simplereq(
915            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
916            $self->editor->authtoken, [$self->cgi->param("payment")]
917         );
918     } else {
919         $self->ctx->{email_receipt_result} =
920             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
921     }
922
923     return Apache2::Const::OK;
924 }
925
926 sub prepare_fines {
927     my ($self, $limit, $offset, $id_list) = @_;
928
929     # XXX TODO: check for failure after various network calls
930
931     # It may be unclear, but this result structure lumps circulation and
932     # reservation fines together, and keeps grocery fines separate.
933     $self->ctx->{"fines"} = {
934         "circulation" => [],
935         "grocery" => [],
936         "total_paid" => 0,
937         "total_owed" => 0,
938         "balance_owed" => 0
939     };
940
941     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
942
943     # TODO: This should really be a ML call, but the existing calls 
944     # return an excessive amount of data and don't offer streaming
945
946     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
947
948     my $req = $cstore->request(
949         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
950         {
951             usr => $self->editor->requestor->id,
952             balance_owed => {'!=' => 0},
953             ($id_list && @$id_list ? ("id" => $id_list) : ()),
954         },
955         {
956             flesh => 4,
957             flesh_fields => {
958                 mobts => [qw/grocery circulation reservation/],
959                 bresv => ['target_resource_type'],
960                 brt => ['record'],
961                 mg => ['billings'],
962                 mb => ['btype'],
963                 circ => ['target_copy'],
964                 acp => ['call_number'],
965                 acn => ['record']
966             },
967             order_by => { mobts => 'xact_start' },
968             %paging
969         }
970     );
971
972     my @total_keys = qw/total_paid total_owed balance_owed/;
973     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
974
975     while(my $resp = $req->recv) {
976         my $mobts = $resp->content;
977         my $circ = $mobts->circulation;
978
979         my $last_billing;
980         if($mobts->grocery) {
981             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
982             $last_billing = pop(@billings);
983         }
984
985         # XXX TODO confirm that the following, and the later division by 100.0
986         # to get a floating point representation once again, is sufficiently
987         # "money-safe" math.
988         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
989
990         my $marc_xml = undef;
991         if ($mobts->xact_type eq 'reservation' and
992             $mobts->reservation->target_resource_type->record) {
993             $marc_xml = XML::LibXML->new->parse_string(
994                 $mobts->reservation->target_resource_type->record->marc
995             );
996         } elsif ($mobts->xact_type eq 'circulation' and
997             $circ->target_copy->call_number->id != -1) {
998             $marc_xml = XML::LibXML->new->parse_string(
999                 $circ->target_copy->call_number->record->marc
1000             );
1001         }
1002
1003         push(
1004             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1005             {
1006                 xact => $mobts,
1007                 last_grocery_billing => $last_billing,
1008                 marc_xml => $marc_xml
1009             } 
1010         );
1011     }
1012
1013     $cstore->kill_me;
1014
1015     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1016     return;
1017 }
1018
1019 sub prepare_fines_for_payment {
1020     # This assumes $self->prepare_fines has already been run
1021     my ($self) = @_;
1022
1023     my @results = ();
1024     if ($self->ctx->{fines}) {
1025         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1026             @{$self->ctx->{fines}->{circulation}},
1027             @{$self->ctx->{fines}->{grocery}}
1028         );
1029     }
1030
1031     return \@results;
1032 }
1033
1034 sub load_myopac_main {
1035     my $self = shift;
1036     my $limit = $self->cgi->param('limit') || 0;
1037     my $offset = $self->cgi->param('offset') || 0;
1038
1039     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1040 }
1041
1042 sub load_myopac_update_email {
1043     my $self = shift;
1044     my $e = $self->editor;
1045     my $ctx = $self->ctx;
1046     my $email = $self->cgi->param('email') || '';
1047
1048     # needed for most up-to-date email address
1049     if (my $r = $self->prepare_extended_user_info) { return $r };
1050
1051     return Apache2::Const::OK 
1052         unless $self->cgi->request_method eq 'POST';
1053
1054     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1055         $ctx->{invalid_email} = $email;
1056         return Apache2::Const::OK;
1057     }
1058
1059     my $stat = $U->simplereq(
1060         'open-ils.actor', 
1061         'open-ils.actor.user.email.update', 
1062         $e->authtoken, $email);
1063
1064     unless ($self->cgi->param("redirect_to")) {
1065         my $url = $self->apache->unparsed_uri;
1066         $url =~ s/update_email/prefs/;
1067
1068         return $self->generic_redirect($url);
1069     }
1070
1071     return $self->generic_redirect;
1072 }
1073
1074 sub load_myopac_update_username {
1075     my $self = shift;
1076     my $e = $self->editor;
1077     my $ctx = $self->ctx;
1078     my $username = $self->cgi->param('username') || '';
1079
1080     return Apache2::Const::OK 
1081         unless $self->cgi->request_method eq 'POST';
1082
1083     unless($username and $username !~ /\s/) { # any other username restrictions?
1084         $ctx->{invalid_username} = $username;
1085         return Apache2::Const::OK;
1086     }
1087
1088     if($username ne $e->requestor->usrname) {
1089
1090         my $evt = $U->simplereq(
1091             'open-ils.actor', 
1092             'open-ils.actor.user.username.update', 
1093             $e->authtoken, $username);
1094
1095         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1096             $ctx->{username_exists} = $username;
1097             return Apache2::Const::OK;
1098         }
1099     }
1100
1101     my $url = $self->apache->unparsed_uri;
1102     $url =~ s/update_username/prefs/;
1103
1104     return $self->generic_redirect($url);
1105 }
1106
1107 sub load_myopac_update_password {
1108     my $self = shift;
1109     my $e = $self->editor;
1110     my $ctx = $self->ctx;
1111
1112     return Apache2::Const::OK 
1113         unless $self->cgi->request_method eq 'POST';
1114
1115     my $current_pw = $self->cgi->param('current_pw') || '';
1116     my $new_pw = $self->cgi->param('new_pw') || '';
1117     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1118
1119     unless($new_pw eq $new_pw2) {
1120         $ctx->{password_nomatch} = 1;
1121         return Apache2::Const::OK;
1122     }
1123
1124     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1125
1126     if($pw_regex and $new_pw !~ /$pw_regex/) {
1127         $ctx->{password_invalid} = 1;
1128         return Apache2::Const::OK;
1129     }
1130
1131     my $evt = $U->simplereq(
1132         'open-ils.actor', 
1133         'open-ils.actor.user.password.update', 
1134         $e->authtoken, $new_pw, $current_pw);
1135
1136
1137     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1138         $ctx->{password_incorrect} = 1;
1139         return Apache2::Const::OK;
1140     }
1141
1142     my $url = $self->apache->unparsed_uri;
1143     $url =~ s/update_password/prefs/;
1144
1145     return $self->generic_redirect($url);
1146 }
1147
1148 sub load_myopac_bookbags {
1149     my $self = shift;
1150     my $e = $self->editor;
1151     my $ctx = $self->ctx;
1152
1153     $e->xact_begin; # replication...
1154
1155     my $rv = $self->load_mylist;
1156     unless($rv eq Apache2::Const::OK) {
1157         $e->rollback;
1158         return $rv;
1159     }
1160
1161     my $args = {
1162         order_by => {cbreb => 'name'},
1163         limit => $self->cgi->param('limit') || 10,
1164         offset => $self->cgi->param('offset') || 0
1165     };
1166
1167     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1168         [
1169             {owner => $self->editor->requestor->id, btype => 'bookbag'},
1170             {"flesh" => 1, "flesh_fields" => {"cbreb" => ["items"]}, %$args}
1171         ], 
1172         {substream => 1}
1173     );
1174
1175     if(!$ctx->{bookbags}) {
1176         $e->rollback;
1177         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1178     }
1179     
1180     # get unique record IDs
1181     my %rec_ids = ();
1182     foreach my $bbag (@{$ctx->{bookbags}}) {
1183         foreach my $rec_id (
1184             map { $_->target_biblio_record_entry } @{$bbag->items}
1185         ) {
1186             $rec_ids{$rec_id} = 1;
1187         }
1188     }
1189
1190     $ctx->{bookbags_marc_xml} = $self->fetch_marc_xml_by_id([keys %rec_ids]);
1191
1192     $e->rollback;
1193     return Apache2::Const::OK;
1194 }
1195
1196
1197 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1198 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1199 sub load_myopac_bookbag_update {
1200     my ($self, $action, $list_id, @hold_recs) = @_;
1201     my $e = $self->editor;
1202     my $cgi = $self->cgi;
1203
1204     $action ||= $cgi->param('action');
1205     $list_id ||= $cgi->param('list');
1206
1207     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1208     my @selected_item = $cgi->param('selected_item');
1209     my $shared = $cgi->param('shared');
1210     my $name = $cgi->param('name');
1211     my $success = 0;
1212     my $list;
1213
1214     if($action eq 'create') {
1215         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1216         $list->name($name);
1217         $list->owner($e->requestor->id);
1218         $list->btype('bookbag');
1219         $list->pub($shared ? 't' : 'f');
1220         $success = $U->simplereq('open-ils.actor', 
1221             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1222
1223     } elsif($action eq 'place_hold') {
1224
1225         # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1226         unless (@hold_recs) {
1227             if (@selected_item) {
1228                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1229                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1230             }
1231         }
1232                 
1233         return Apache2::Const::OK unless @hold_recs;
1234         $logger->info("placing holds from list page on: @hold_recs");
1235
1236         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1237         $url .= ';hold_target=' . $_ for @hold_recs;
1238         return $self->generic_redirect($url);
1239
1240     } else {
1241
1242         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1243
1244         return Apache2::Const::HTTP_BAD_REQUEST unless 
1245             $list and $list->owner == $e->requestor->id;
1246     }
1247
1248     if($action eq 'delete') {
1249         $success = $U->simplereq('open-ils.actor', 
1250             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1251
1252     } elsif($action eq 'show') {
1253         unless($U->is_true($list->pub)) {
1254             $list->pub('t');
1255             $success = $U->simplereq('open-ils.actor', 
1256                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1257         }
1258
1259     } elsif($action eq 'hide') {
1260         if($U->is_true($list->pub)) {
1261             $list->pub('f');
1262             $success = $U->simplereq('open-ils.actor', 
1263                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1264         }
1265
1266     } elsif($action eq 'rename') {
1267         if($name) {
1268             $list->name($name);
1269             $success = $U->simplereq('open-ils.actor', 
1270                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1271         }
1272
1273     } elsif($action eq 'add_rec') {
1274         foreach my $add_rec (@add_rec) {
1275             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1276             $item->bucket($list_id);
1277             $item->target_biblio_record_entry($add_rec);
1278             $success = $U->simplereq('open-ils.actor', 
1279                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1280             last unless $success;
1281         }
1282
1283     } elsif($action eq 'del_item') {
1284         foreach (@selected_item) {
1285             $success = $U->simplereq(
1286                 'open-ils.actor',
1287                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1288             );
1289             last unless $success;
1290         }
1291     }
1292
1293     return $self->generic_redirect if $success;
1294
1295     $self->ctx->{bucket_action} = $action;
1296     $self->ctx->{bucket_action_failed} = 1;
1297     return Apache2::Const::OK;
1298 }
1299
1300 1