]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
Z39.50 Batch Search/Overlay TPAC my-list entry point
[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 OpenSRF::Utils::Cache;
11 use Digest::MD5 qw(md5_hex);
12 use Data::Dumper;
13 $Data::Dumper::Indent = 0;
14 use DateTime;
15 my $U = 'OpenILS::Application::AppUtils';
16
17 sub prepare_extended_user_info {
18     my $self = shift;
19     my @extra_flesh = @_;
20     my $e = $self->editor;
21
22     # are we already in a transaction?
23     my $local_xact = !$e->{xact_id}; 
24     $e->xact_begin if $local_xact;
25
26     # keep the original user object so we can restore
27     # login-specific data (e.g. workstation)
28     my $usr = $self->ctx->{user};
29
30     $self->ctx->{user} = $self->editor->retrieve_actor_user([
31         $self->ctx->{user}->id,
32         {
33             flesh => 1,
34             flesh_fields => {
35                 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
36                 # ...
37             }
38         }
39     ]);
40
41     $e->rollback if $local_xact;
42
43     $self->ctx->{user}->wsid($usr->wsid);
44     $self->ctx->{user}->ws_ou($usr->ws_ou);
45
46     # discard replaced (negative-id) addresses.
47     $self->ctx->{user}->addresses([
48         grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
49
50     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR 
51         unless $self->ctx->{user};
52
53     return;
54 }
55
56 # Given an event returned by a failed attempt to create a hold, do we have
57 # permission to override?  XXX Should the permission check be scoped to a
58 # given org_unit context?
59 sub test_could_override {
60     my ($self, $event) = @_;
61
62     return 0 unless $event;
63     return 1 if $self->editor->allowed($event->{textcode} . ".override");
64     return 1 if $event->{"fail_part"} and
65         $self->editor->allowed($event->{"fail_part"} . ".override");
66     return 0;
67 }
68
69 # Find out whether we care that local copies are available
70 sub local_avail_concern {
71     my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
72
73     my $would_block = $self->ctx->{get_org_setting}->
74         ($pickup_lib, "circ.holds.hold_has_copy_at.block");
75     my $would_alert = (
76         $self->ctx->{get_org_setting}->
77             ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
78                 not $self->cgi->param("override")
79     ) unless $would_block;
80
81     if ($would_block or $would_alert) {
82         my $args = {
83             "hold_target" => $hold_target,
84             "hold_type" => $hold_type,
85             "org_unit" => $pickup_lib
86         };
87         my $local_avail = $U->simplereq(
88             "open-ils.circ",
89             "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
90         );
91         $logger->info(
92             "copy availability information for " . Dumper($args) .
93             " is " . Dumper($local_avail)
94         );
95         if (%$local_avail) { # if hash not empty
96             $self->ctx->{hold_copy_available} = $local_avail;
97             return ($would_block, $would_alert);
98         }
99     }
100
101     return (0, 0);
102 }
103
104 # context additions: 
105 #   user : au object, fleshed
106 sub load_myopac_prefs {
107     my $self = shift;
108     my $cgi = $self->cgi;
109     my $e = $self->editor;
110     my $pending_addr = $cgi->param('pending_addr');
111     my $replace_addr = $cgi->param('replace_addr');
112     my $delete_pending = $cgi->param('delete_pending');
113
114     $self->prepare_extended_user_info;
115     my $user = $self->ctx->{user};
116
117     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
118     if(defined($lock_usernames) and $lock_usernames == 1) {
119         # Policy says no username changes
120         $self->ctx->{username_change_disallowed} = 1;
121     } else {
122         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
123         if(!$username_unlimit) {
124             my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
125             if(!$regex_check) {
126                 # Default is "starts with a number"
127                 $regex_check = '^\d+';
128             }
129             # You already have a username?
130             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
131                 $self->ctx->{username_change_disallowed} = 1;
132             }
133         }
134     }
135
136     return Apache2::Const::OK unless 
137         $pending_addr or $replace_addr or $delete_pending;
138
139     my @form_fields = qw/address_type street1 street2 city county state country post_code/;
140
141     my $paddr;
142     if( $pending_addr ) { # update an existing pending address
143
144         ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
145         return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
146         $paddr->$_( $cgi->param($_) ) for @form_fields;
147
148     } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
149
150         $paddr = Fieldmapper::actor::user_address->new;
151         $paddr->isnew(1);
152         $paddr->usr($user->id);
153         $paddr->pending('t');
154         $paddr->replaces($replace_addr);
155         $paddr->$_( $cgi->param($_) ) for @form_fields;
156
157     } elsif( $delete_pending ) {
158         $paddr = $e->retrieve_actor_user_address($delete_pending);
159         return Apache2::Const::HTTP_BAD_REQUEST unless 
160             $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
161         $paddr->isdeleted(1);
162     }
163
164     my $resp = $U->simplereq(
165         'open-ils.actor', 
166         'open-ils.actor.user.address.pending.cud',
167         $e->authtoken, $paddr);
168
169     if( $U->event_code($resp) ) {
170         $logger->error("Error updating pending address: $resp");
171         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
172     }
173
174     # in light of these changes, re-fetch latest data
175     $e->xact_begin; 
176     $self->prepare_extended_user_info;
177     $e->rollback;
178
179     return Apache2::Const::OK;
180 }
181
182 sub load_myopac_prefs_notify {
183     my $self = shift;
184     my $e = $self->editor;
185
186
187     my $stat = $self->_load_user_with_prefs;
188     return $stat if $stat;
189
190     my $user_prefs = $self->fetch_optin_prefs;
191     $user_prefs = $self->update_optin_prefs($user_prefs)
192         if $self->cgi->request_method eq 'POST';
193
194     $self->ctx->{opt_in_settings} = $user_prefs;
195
196     return Apache2::Const::OK
197         unless $self->cgi->request_method eq 'POST';
198
199     my %settings;
200     my $set_map = $self->ctx->{user_setting_map};
201  
202     foreach my $key (qw/
203         opac.default_phone
204         opac.default_sms_notify
205     /) {
206         my $val = $self->cgi->param($key);
207         $settings{$key}= $val unless $$set_map{$key} eq $val;
208     }
209
210     my $key = 'opac.default_sms_carrier';
211     my $val = $self->cgi->param('sms_carrier');
212     $settings{$key}= $val unless $$set_map{$key} eq $val;
213
214     $key = 'opac.hold_notify';
215     my @notify_methods = ();
216     if ($self->cgi->param($key . ".email") eq 'on') {
217         push @notify_methods, "email";
218     }
219     if ($self->cgi->param($key . ".phone") eq 'on') {
220         push @notify_methods, "phone";
221     }
222     if ($self->cgi->param($key . ".sms") eq 'on') {
223         push @notify_methods, "sms";
224     }
225     $val = join("|",@notify_methods);
226     $settings{$key}= $val unless $$set_map{$key} eq $val;
227
228     # Send the modified settings off to be saved
229     $U->simplereq(
230         'open-ils.actor', 
231         'open-ils.actor.patron.settings.update',
232         $self->editor->authtoken, undef, \%settings);
233
234     # re-fetch user prefs 
235     $self->ctx->{updated_user_settings} = \%settings;
236     return $self->_load_user_with_prefs || Apache2::Const::OK;
237 }
238
239 sub fetch_optin_prefs {
240     my $self = shift;
241     my $e = $self->editor;
242
243     # fetch all of the opt-in settings the user has access to
244     # XXX: user's should in theory have options to opt-in to notices
245     # for remote locations, but that opens the door for a large
246     # set of generally un-used opt-ins.. needs discussion
247     my $opt_ins =  $U->simplereq(
248         'open-ils.actor',
249         'open-ils.actor.event_def.opt_in.settings.atomic',
250         $e->authtoken, $e->requestor->home_ou);
251
252     # some opt-ins are staff-only
253     $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
254
255     # fetch user setting values for each of the opt-in settings
256     my $user_set = $U->simplereq(
257         'open-ils.actor',
258         'open-ils.actor.patron.settings.retrieve',
259         $e->authtoken, 
260         $e->requestor->id, 
261         [map {$_->name} @$opt_ins]
262     );
263
264     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
265 }
266
267 sub _load_lists_and_settings {
268     my $self = shift;
269     my $e = $self->editor;
270     my $stat = $self->_load_user_with_prefs;
271     unless ($stat) {
272         my $exclude = 0;
273         my $setting_map = $self->ctx->{user_setting_map};
274         $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
275         $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
276             [
277                 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
278                     order_by => {cbreb => 'name'},
279                     limit => $self->cgi->param('limit') || 10,
280                     offset => $self->cgi->param('offset') || 0
281                 }
282             ]
283         );
284         # We also want a total count of the user's bookbags.
285         my $q = {
286             'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
287             'from' => 'cbreb',
288             'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
289         };
290         my $r = $e->json_query($q);
291         $self->ctx->{bookbag_count} = $r->[0]->{'count'};
292         # Someone has requested that we use the default list's name
293         # rather than "Default List."
294         if ($exclude) {
295             $q = {
296                 'select' => {'cbreb' => ['name']},
297                 'from' => 'cbreb',
298                 'where' => {'id' => $exclude}
299             };
300             $r = $e->json_query($q);
301             $self->ctx->{default_bookbag} = $r->[0]->{'name'};
302         }
303     } else {
304         return $stat;
305     }
306     return undef;
307 }
308
309 sub update_optin_prefs {
310     my $self = shift;
311     my $user_prefs = shift;
312     my $e = $self->editor;
313     my @settings = $self->cgi->param('setting');
314     my %newsets;
315
316     # apply now-true settings
317     for my $applied (@settings) {
318         # see if setting is already applied to this user
319         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
320         $newsets{$applied} = OpenSRF::Utils::JSON->true;
321     }
322
323     # remove now-false settings
324     for my $pref (grep { $_->{value} } @$user_prefs) {
325         $newsets{$pref->{cust}->name} = undef 
326             unless grep { $_ eq $pref->{cust}->name } @settings;
327     }
328
329     $U->simplereq(
330         'open-ils.actor',
331         'open-ils.actor.patron.settings.update',
332         $e->authtoken, $e->requestor->id, \%newsets);
333
334     # update the local prefs to match reality
335     for my $pref (@$user_prefs) {
336         $pref->{value} = $newsets{$pref->{cust}->name} 
337             if exists $newsets{$pref->{cust}->name};
338     }
339
340     return $user_prefs;
341 }
342
343 sub _load_user_with_prefs {
344     my $self = shift;
345     my $stat = $self->prepare_extended_user_info('settings');
346     return $stat if $stat; # not-OK
347
348     $self->ctx->{user_setting_map} = {
349         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) } 
350             @{$self->ctx->{user}->settings}
351     };
352
353     return undef;
354 }
355
356 sub _get_bookbag_sort_params {
357     my ($self, $param_name) = @_;
358
359     # The interface that feeds this cgi parameter will provide a single
360     # argument for a QP sort filter, and potentially a modifier after a period.
361     # In practice this means the "sort" parameter will be something like
362     # "titlesort" or "authorsort.descending".
363     my $sorter = $self->cgi->param($param_name) || "";
364     my $modifier;
365     if ($sorter) {
366         $sorter =~ s/^(.*?)\.(.*)/$1/;
367         $modifier = $2 || undef;
368     }
369
370     return ($sorter, $modifier);
371 }
372
373 sub _prepare_bookbag_container_query {
374     my ($self, $container_id, $sorter, $modifier) = @_;
375
376     return sprintf(
377         "container(bre,bookbag,%d,%s)%s%s",
378         $container_id, $self->editor->authtoken,
379         ($sorter ? " sort($sorter)" : ""),
380         ($modifier ? "#$modifier" : "")
381     );
382 }
383
384 sub _prepare_anonlist_sorting_query {
385     my ($self, $list, $sorter, $modifier) = @_;
386
387     return sprintf(
388         "record_list(%s)%s%s",
389         join(",", @$list),
390         ($sorter ? " sort($sorter)" : ""),
391         ($modifier ? "#$modifier" : "")
392     );
393 }
394
395
396 sub load_myopac_prefs_settings {
397     my $self = shift;
398
399     my @user_prefs = qw/
400         opac.hits_per_page
401         opac.default_search_location
402         opac.default_pickup_location
403         opac.temporary_list_no_warn
404     /;
405
406     my $stat = $self->_load_user_with_prefs;
407     return $stat if $stat;
408
409     return Apache2::Const::OK
410         unless $self->cgi->request_method eq 'POST';
411
412     # some setting values from the form don't match the 
413     # required value/format for the db, so they have to be 
414     # individually translated.
415
416     my %settings;
417     my $set_map = $self->ctx->{user_setting_map};
418
419     foreach my $key (@user_prefs) {
420         my $val = $self->cgi->param($key);
421         $settings{$key}= $val unless $$set_map{$key} eq $val;
422     }
423
424     my $now = DateTime->now->strftime('%F');
425     foreach my $key (qw/history.circ.retention_start history.hold.retention_start/) {
426         my $val = $self->cgi->param($key);
427         if($val and $val eq 'on') {
428             # Set the start time to 'now' unless a start time already exists for the user
429             $settings{$key} = $now unless $$set_map{$key};
430         } else {
431             # clear the start time if one previously existed for the user
432             $settings{$key} = undef if $$set_map{$key};
433         }
434     }
435
436     # Send the modified settings off to be saved
437     $U->simplereq(
438         'open-ils.actor', 
439         'open-ils.actor.patron.settings.update',
440         $self->editor->authtoken, undef, \%settings);
441
442     # re-fetch user prefs 
443     $self->ctx->{updated_user_settings} = \%settings;
444     return $self->_load_user_with_prefs || Apache2::Const::OK;
445 }
446
447 sub fetch_user_holds {
448     my $self = shift;
449     my $hold_ids = shift;
450     my $ids_only = shift;
451     my $flesh = shift;
452     my $available = shift;
453     my $limit = shift;
454     my $offset = shift;
455
456     my $e = $self->editor;
457     my $all_ids; # to be used below.
458
459     if(!$hold_ids) {
460         my $circ = OpenSRF::AppSession->create('open-ils.circ');
461
462         $hold_ids = $circ->request(
463             'open-ils.circ.holds.id_list.retrieve.authoritative', 
464             $e->authtoken, 
465             $e->requestor->id,
466             $available
467         )->gather(1);
468         $circ->kill_me;
469
470         $all_ids = $hold_ids;
471         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
472
473     } else {
474         $all_ids = $hold_ids;
475     }
476
477     return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
478
479     my $args = {
480         suppress_notices => 1,
481         suppress_transits => 1,
482         suppress_mvr => 1,
483         suppress_patron_details => 1
484     };
485
486     # ----------------------------------------------------------------
487     # Collect holds in batches of $batch_size for faster retrieval
488
489     my $batch_size = 8;
490     my $batch_idx = 0;
491     my $mk_req_batch = sub {
492         my @ses;
493         my $top_idx = $batch_idx + $batch_size;
494         while($batch_idx < $top_idx) {
495             my $hold_id = $hold_ids->[$batch_idx++];
496             last unless $hold_id;
497             my $ses = OpenSRF::AppSession->create('open-ils.circ');
498             my $req = $ses->request(
499                 'open-ils.circ.hold.details.retrieve', 
500                 $e->authtoken, $hold_id, $args);
501             push(@ses, {ses => $ses, req => $req});
502         }
503         return @ses;
504     };
505
506     my $first = 1;
507     my(@collected, @holds, @ses);
508
509     while(1) {
510         @ses = $mk_req_batch->() if $first;
511         last if $first and not @ses;
512
513         if(@collected) {
514             while(my $blob = pop(@collected)) {
515                 my (undef, @data) = $self->get_records_and_facets(
516                     [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
517                 );
518                 $blob->{marc_xml} = $data[0]->{marc_xml};
519                 push(@holds, $blob);
520             }
521         }
522
523         for my $req_data (@ses) {
524             push(@collected, {hold => $req_data->{req}->gather(1)});
525             $req_data->{ses}->kill_me;
526         }
527
528         @ses = $mk_req_batch->();
529         last unless @collected or @ses;
530         $first = 0;
531     }
532
533     # put the holds back into the original server sort order
534     my @sorted;
535     for my $id (@$hold_ids) {
536         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
537     }
538
539     return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids };
540 }
541
542 sub handle_hold_update {
543     my $self = shift;
544     my $action = shift;
545     my $hold_ids = shift;
546     my $e = $self->editor;
547     my $url;
548
549     my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
550     @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
551
552     my $circ = OpenSRF::AppSession->create('open-ils.circ');
553
554     if($action =~ /cancel/) {
555
556         for my $hold_id (@hold_ids) {
557             my $resp = $circ->request(
558                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
559         }
560
561     } elsif ($action =~ /activate|suspend/) {
562         
563         my $vlist = [];
564         for my $hold_id (@hold_ids) {
565             my $vals = {id => $hold_id};
566
567             if($action =~ /activate/) {
568                 $vals->{frozen} = 'f';
569                 $vals->{thaw_date} = undef;
570
571             } elsif($action =~ /suspend/) {
572                 $vals->{frozen} = 't';
573                 # $vals->{thaw_date} = TODO;
574             }
575             push(@$vlist, $vals);
576         }
577
578         my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
579         $self->ctx->{hold_suspend_post_capture} = 1 if 
580             grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
581
582     } elsif ($action eq 'edit') {
583
584         my @vals = map {
585             my $val = {"id" => $_};
586             $val->{"frozen"} = $self->cgi->param("frozen");
587             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
588
589             for my $field (qw/expire_time thaw_date/) {
590                 # XXX TODO make this support other date formats, not just
591                 # MM/DD/YYYY.
592                 next unless $self->cgi->param($field) =~
593                     m:^(\d{2})/(\d{2})/(\d{4})$:;
594                 $val->{$field} = "$3-$1-$2";
595             }
596             $val;
597         } @hold_ids;
598
599         $circ->request(
600             'open-ils.circ.hold.update.batch.atomic',
601             $e->authtoken, undef, \@vals
602         )->gather(1);   # LFW XXX test for failure
603         $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
604         foreach my $param (('loc', 'qtype', 'query')) {
605             if ($self->cgi->param($param)) {
606                 $url .= ";$param=" . uri_escape($self->cgi->param($param));
607             }
608         }
609     }
610
611     $circ->kill_me;
612     return defined($url) ? $self->generic_redirect($url) : undef;
613 }
614
615 sub load_myopac_holds {
616     my $self = shift;
617     my $e = $self->editor;
618     my $ctx = $self->ctx;
619     
620     my $limit = $self->cgi->param('limit') || 15;
621     my $offset = $self->cgi->param('offset') || 0;
622     my $action = $self->cgi->param('action') || '';
623     my $hold_id = $self->cgi->param('id');
624     my $available = int($self->cgi->param('available') || 0);
625
626     my $hold_handle_result;
627     $hold_handle_result = $self->handle_hold_update($action) if $action;
628
629     my $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
630     if($holds_object->{holds}) {
631         $ctx->{holds} = $holds_object->{holds};
632     }
633     $ctx->{holds_ids} = $holds_object->{all_ids};
634     $ctx->{holds_limit} = $limit;
635     $ctx->{holds_offset} = $offset;
636
637     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
638 }
639
640 my $data_filler;
641
642 sub load_place_hold {
643     my $self = shift;
644     my $ctx = $self->ctx;
645     my $gos = $ctx->{get_org_setting};
646     my $e = $self->editor;
647     my $cgi = $self->cgi;
648
649     $self->ctx->{page} = 'place_hold';
650     my @targets = $cgi->param('hold_target');
651     my @parts = $cgi->param('part');
652
653     $ctx->{hold_type} = $cgi->param('hold_type');
654     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
655     $ctx->{email_notify} = $cgi->param('email_notify');
656     if ($cgi->param('phone_notify_checkbox')) {
657         $ctx->{phone_notify} = $cgi->param('phone_notify');
658     }
659     if ($cgi->param('sms_notify_checkbox')) {
660         $ctx->{sms_notify} = $cgi->param('sms_notify');
661         $ctx->{sms_carrier} = $cgi->param('sms_carrier');
662     }
663
664     return $self->generic_redirect unless @targets;
665
666     $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
667
668     $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
669         $e->requestor->id,
670         {
671             flesh => 1,
672             flesh_fields => {
673                 au => ['settings', 'card']
674             }
675         }
676     ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
677     my $user_setting_map = {
678         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
679             @{
680                 $ctx->{staff_recipient}->settings
681             }
682     };
683     $ctx->{user_setting_map} = $user_setting_map;
684
685     my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
686     if ($default_notify =~ /email/) {
687         $ctx->{default_email_notify} = 'checked';
688     } else {
689         $ctx->{default_email_notify} = '';
690     }
691     if ($default_notify =~ /phone/) {
692         $ctx->{default_phone_notify} = 'checked';
693     } else {
694         $ctx->{default_phone_notify} = '';
695     }
696     if ($default_notify =~ /sms/) {
697         $ctx->{default_sms_notify} = 'checked';
698     } else {
699         $ctx->{default_sms_notify} = '';
700     }
701
702     # If we have a default pickup location, grab it
703     if ($$user_setting_map{'opac.default_pickup_location'}) {
704         $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
705     }
706
707     my $request_lib = $e->requestor->ws_ou;
708     my @hold_data;
709     $ctx->{hold_data} = \@hold_data;
710
711     $data_filler = sub {
712         my $hdata = shift;
713         if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
714         if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
715         if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
716         if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
717         return $hdata;
718     };
719
720     my $type_dispatch = {
721         T => sub {
722             my $recs = $e->batch_retrieve_biblio_record_entry(\@targets, {substream => 1});
723
724             for my $id (@targets) { # force back into the correct order
725                 my ($rec) = grep {$_->id eq $id} @$recs;
726
727                 # NOTE: if tpac ever supports locked-down pickup libs,
728                 # we'll need to pass a pickup_lib param along with the 
729                 # record to filter the set of monographic parts.
730                 my $parts = $U->simplereq(
731                     'open-ils.search',
732                     'open-ils.search.biblio.record_hold_parts', 
733                     {record => $rec->id}
734                 );
735
736                 # T holds on records that have parts are OK, but if the record has 
737                 # no non-part copies, the hold will ultimately fail.  When that 
738                 # happens, require the user to select a part.
739                 my $part_required = 0;
740                 if (@$parts) {
741                     my $np_copies = $e->json_query({
742                         select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]}, 
743                         from => {acp => {acn => {}, acpm => {type => 'left'}}}, 
744                         where => {
745                             '+acp' => {deleted => 'f'},
746                             '+acn' => {deleted => 'f', record => $rec->id}, 
747                             '+acpm' => {id => undef}
748                         }
749                     });
750                     $part_required = 1 if $np_copies->[0]->{count} == 0;
751                 }
752
753                 push(@hold_data, $data_filler->({
754                     target => $rec,
755                     record => $rec,
756                     parts => $parts,
757                     part_required => $part_required
758                 }));
759             }
760         },
761         V => sub {
762             my $vols = $e->batch_retrieve_asset_call_number([
763                 \@targets, {
764                     "flesh" => 1,
765                     "flesh_fields" => {"acn" => ["record"]}
766                 }
767             ], {substream => 1});
768
769             for my $id (@targets) { 
770                 my ($vol) = grep {$_->id eq $id} @$vols;
771                 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
772             }
773         },
774         C => sub {
775             my $copies = $e->batch_retrieve_asset_copy([
776                 \@targets, {
777                     "flesh" => 2,
778                     "flesh_fields" => {
779                         "acn" => ["record"],
780                         "acp" => ["call_number"]
781                     }
782                 }
783             ], {substream => 1});
784
785             for my $id (@targets) { 
786                 my ($copy) = grep {$_->id eq $id} @$copies;
787                 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
788             }
789         },
790         I => sub {
791             my $isses = $e->batch_retrieve_serial_issuance([
792                 \@targets, {
793                     "flesh" => 2,
794                     "flesh_fields" => {
795                         "siss" => ["subscription"], "ssub" => ["record_entry"]
796                     }
797                 }
798             ], {substream => 1});
799
800             for my $id (@targets) { 
801                 my ($iss) = grep {$_->id eq $id} @$isses;
802                 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
803             }
804         }
805         # ...
806
807     }->{$ctx->{hold_type}}->();
808
809     # caller sent bad target IDs or the wrong hold type
810     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
811
812     # generate the MARC xml for each record
813     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
814
815     my $pickup_lib = $cgi->param('pickup_lib');
816     # no pickup lib means no holds placement
817     return Apache2::Const::OK unless $pickup_lib;
818
819     $ctx->{hold_attempt_made} = 1;
820
821     # Give the original CGI params back to the user in case they
822     # want to try to override something.
823     $ctx->{orig_params} = $cgi->Vars;
824     delete $ctx->{orig_params}{submit};
825     delete $ctx->{orig_params}{hold_target};
826     delete $ctx->{orig_params}{part};
827
828     my $usr = $e->requestor->id;
829
830     if ($ctx->{is_staff} and !$cgi->param("hold_usr_is_requestor")) {
831         # find the real hold target
832
833         $usr = $U->simplereq(
834             'open-ils.actor', 
835             "open-ils.actor.user.retrieve_id_by_barcode_or_username",
836             $e->authtoken, $cgi->param("hold_usr"));
837
838         if (defined $U->event_code($usr)) {
839             $ctx->{hold_failed} = 1;
840             $ctx->{hold_failed_event} = $usr;
841         }
842     }
843
844     # target_id is the true target_id for holds placement.  
845     # needed for attempt_hold_placement()
846     # With the exception of P-type holds, target_id == target->id.
847     $_->{target_id} = $_->{target}->id for @hold_data;
848
849     if ($ctx->{hold_type} eq 'T') {
850
851         # Much like quantum wave-particles, P-type holds pop into 
852         # and out of existence at the user's whim.  For our purposes,
853         # we treat such holds as T(itle) holds with a selected_part 
854         # designation.  When the time comes to pass the hold information 
855         # off for holds possibility testing and placement, make it look 
856         # like a real P-type hold.
857         my (@p_holds, @t_holds);
858         
859         for my $idx (0..$#parts) {
860             my $hdata = $hold_data[$idx];
861             if (my $part = $parts[$idx]) {
862                 $hdata->{target_id} = $part;
863                 $hdata->{selected_part} = $part;
864                 push(@p_holds, $hdata);
865             } else {
866                 push(@t_holds, $hdata);
867             }
868         }
869
870         $self->apache->log->warn("$#parts : @t_holds");
871
872         $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
873         $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
874
875     } else {
876         $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
877     }
878
879     # NOTE: we are leaving the staff-placed patron barcode cookie 
880     # in place.  Otherwise, it's not possible to place more than 
881     # one hold for the patron within a staff/patron session.  This 
882     # does leave the barcode to linger longer than is ideal, but 
883     # normal staff work flow will cause the cookie to be replaced 
884     # with each new patron anyway.
885     # TODO: See about getting the staff client to clear the cookie
886
887     # return to the place_hold page so the results of the hold
888     # placement attempt can be reported to the user
889     return Apache2::Const::OK;
890 }
891
892 sub attempt_hold_placement {
893     my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
894     my $cgi = $self->cgi;
895     my $ctx = $self->ctx;
896     my $e = $self->editor;
897
898     # First see if we should warn/block for any holds that 
899     # might have locally available items.
900     for my $hdata (@hold_data) {
901         my ($local_block, $local_alert) = $self->local_avail_concern(
902             $hdata->{target_id}, $hold_type, $pickup_lib);
903     
904         if ($local_block) {
905             $hdata->{hold_failed} = 1;
906             $hdata->{hold_local_block} = 1;
907         } elsif ($local_alert) {
908             $hdata->{hold_failed} = 1;
909             $hdata->{hold_local_alert} = 1;
910         }
911     }
912
913     my $method = 'open-ils.circ.holds.test_and_create.batch';
914
915     if ($cgi->param('override')) {
916         $method .= '.override';
917
918     } elsif (!$ctx->{is_staff})  {
919
920         $method .= '.override' if $self->ctx->{get_org_setting}->(
921             $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
922     }
923
924     my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
925
926     if(@create_targets) {
927
928         my $bses = OpenSRF::AppSession->create('open-ils.circ');
929         my $breq = $bses->request( 
930             $method, 
931             $e->authtoken, 
932             $data_filler->({   patronid => $usr,
933                 pickup_lib => $pickup_lib, 
934                 hold_type => $hold_type
935             }),
936             \@create_targets
937         );
938
939         while (my $resp = $breq->recv) {
940
941             $resp = $resp->content;
942             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
943
944             if ($U->event_code($resp)) {
945                 $ctx->{general_hold_error} = $resp;
946                 last;
947             }
948
949             my ($hdata) = grep {$_->{target_id} eq $resp->{target}} @hold_data;
950             my $result = $resp->{result};
951
952             if ($U->event_code($result)) {
953                 # e.g. permission denied
954                 $hdata->{hold_failed} = 1;
955                 $hdata->{hold_failed_event} = $result;
956
957             } else {
958                 
959                 if(not ref $result and $result > 0) {
960                     # successul hold returns the hold ID
961
962                     $hdata->{hold_success} = $result; 
963     
964                 } else {
965                     # hold-specific failure event 
966                     $hdata->{hold_failed} = 1;
967
968                     if (ref $result eq 'HASH') {
969                         $hdata->{hold_failed_event} = $result->{last_event};
970
971                         if ($result->{age_protected_copy}) {
972                             $hdata->{could_override} = 1;
973                             $hdata->{age_protect} = 1;
974                         } else {
975                             $hdata->{could_override} = $result->{place_unfillable} || 
976                                 $self->test_could_override($hdata->{hold_failed_event});
977                         }
978                     } elsif (ref $result eq 'ARRAY') {
979                         $hdata->{hold_failed_event} = $result->[0];
980
981                         if ($result->[3]) { # age_protect_only
982                             $hdata->{could_override} = 1;
983                             $hdata->{age_protect} = 1;
984                         } else {
985                             $hdata->{could_override} = $result->[4] || # place_unfillable
986                                 $self->test_could_override($hdata->{hold_failed_event});
987                         }
988                     }
989                 }
990             }
991         }
992
993         $bses->kill_me;
994     }
995 }
996
997 sub fetch_user_circs {
998     my $self = shift;
999     my $flesh = shift; # flesh bib data, etc.
1000     my $circ_ids = shift;
1001     my $limit = shift;
1002     my $offset = shift;
1003
1004     my $e = $self->editor;
1005
1006     my @circ_ids;
1007
1008     if($circ_ids) {
1009         @circ_ids = @$circ_ids;
1010
1011     } else {
1012
1013         my $query = {
1014             select => {circ => ['id']},
1015             from => 'circ',
1016             where => {
1017                 '+circ' => {
1018                     usr => $e->requestor->id,
1019                     checkin_time => undef,
1020                     '-or' => [
1021                         {stop_fines => undef},
1022                         {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
1023                     ],
1024                 }
1025             },
1026             order_by => {circ => ['due_date']}
1027         };
1028
1029         $query->{limit} = $limit if $limit;
1030         $query->{offset} = $offset if $offset;
1031
1032         my $ids = $e->json_query($query);
1033         @circ_ids = map {$_->{id}} @$ids;
1034     }
1035
1036     return [] unless @circ_ids;
1037
1038     my $qflesh = {
1039         flesh => 3,
1040         flesh_fields => {
1041             circ => ['target_copy'],
1042             acp => ['call_number'],
1043             acn => ['record']
1044         }
1045     };
1046
1047     $e->xact_begin;
1048     my $circs = $e->search_action_circulation(
1049         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
1050
1051     my @circs;
1052     for my $circ (@$circs) {
1053         push(@circs, {
1054             circ => $circ, 
1055             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
1056                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
1057                 undef  # pre-cat copy, use the dummy title/author instead
1058         });
1059     }
1060     $e->xact_rollback;
1061
1062     # make sure the final list is in the correct order
1063     my @sorted_circs;
1064     for my $id (@circ_ids) {
1065         push(
1066             @sorted_circs,
1067             (grep { $_->{circ}->id == $id } @circs)
1068         );
1069     }
1070
1071     return \@sorted_circs;
1072 }
1073
1074
1075 sub handle_circ_renew {
1076     my $self = shift;
1077     my $action = shift;
1078     my $ctx = $self->ctx;
1079
1080     my @renew_ids = $self->cgi->param('circ');
1081
1082     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
1083
1084     # TODO: fire off renewal calls in batches to speed things up
1085     my @responses;
1086     for my $circ (@$circs) {
1087
1088         my $evt = $U->simplereq(
1089             'open-ils.circ', 
1090             'open-ils.circ.renew',
1091             $self->editor->authtoken,
1092             {
1093                 patron_id => $self->editor->requestor->id,
1094                 copy_id => $circ->{circ}->target_copy,
1095                 opac_renewal => 1
1096             }
1097         );
1098
1099         # TODO return these, then insert them into the circ data 
1100         # blob that is shoved into the template for each circ
1101         # so the template won't have to match them
1102         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
1103     }
1104
1105     return @responses;
1106 }
1107
1108
1109 sub load_myopac_circs {
1110     my $self = shift;
1111     my $e = $self->editor;
1112     my $ctx = $self->ctx;
1113
1114     $ctx->{circs} = [];
1115     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
1116     my $offset = $self->cgi->param('offset') || 0;
1117     my $action = $self->cgi->param('action') || '';
1118
1119     # perform the renewal first if necessary
1120     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
1121
1122     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
1123
1124     my $success_renewals = 0;
1125     my $failed_renewals = 0;
1126     for my $data (@{$ctx->{circs}}) {
1127         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
1128
1129         if($resp) {
1130             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
1131             $data->{renewal_response} = $evt;
1132             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
1133             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
1134         }
1135     }
1136
1137     $ctx->{success_renewals} = $success_renewals;
1138     $ctx->{failed_renewals} = $failed_renewals;
1139
1140     return Apache2::Const::OK;
1141 }
1142
1143 sub load_myopac_circ_history {
1144     my $self = shift;
1145     my $e = $self->editor;
1146     my $ctx = $self->ctx;
1147     my $limit = $self->cgi->param('limit') || 15;
1148     my $offset = $self->cgi->param('offset') || 0;
1149
1150     $ctx->{circ_history_limit} = $limit;
1151     $ctx->{circ_history_offset} = $offset;
1152
1153     my $circ_ids = $e->json_query({
1154         select => {
1155             au => [{
1156                 column => 'id', 
1157                 transform => 'action.usr_visible_circs', 
1158                 result_field => 'id'
1159             }]
1160         },
1161         from => 'au',
1162         where => {id => $e->requestor->id}, 
1163         limit => $limit,
1164         offset => $offset
1165     });
1166
1167     $ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circ_ids]);
1168     return Apache2::Const::OK;
1169 }
1170
1171 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
1172 sub load_myopac_hold_history {
1173     my $self = shift;
1174     my $e = $self->editor;
1175     my $ctx = $self->ctx;
1176     my $limit = $self->cgi->param('limit') || 15;
1177     my $offset = $self->cgi->param('offset') || 0;
1178     $ctx->{hold_history_limit} = $limit;
1179     $ctx->{hold_history_offset} = $offset;
1180
1181     my $hold_ids = $e->json_query({
1182         select => {
1183             au => [{
1184                 column => 'id', 
1185                 transform => 'action.usr_visible_holds', 
1186                 result_field => 'id'
1187             }]
1188         },
1189         from => 'au',
1190         where => {id => $e->requestor->id}
1191     });
1192
1193     my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
1194     if($holds_object->{holds}) {
1195         $ctx->{holds} = $holds_object->{holds};
1196     }
1197     $ctx->{hold_history_ids} = $holds_object->{all_ids};
1198
1199     return Apache2::Const::OK;
1200 }
1201
1202 sub load_myopac_payment_form {
1203     my $self = shift;
1204     my $r;
1205
1206     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
1207     $r = $self->prepare_extended_user_info and return $r;
1208
1209     return Apache2::Const::OK;
1210 }
1211
1212 # TODO: add other filter options as params/configs/etc.
1213 sub load_myopac_payments {
1214     my $self = shift;
1215     my $limit = $self->cgi->param('limit') || 20;
1216     my $offset = $self->cgi->param('offset') || 0;
1217     my $e = $self->editor;
1218
1219     $self->ctx->{payment_history_limit} = $limit;
1220     $self->ctx->{payment_history_offset} = $offset;
1221
1222     my $args = {};
1223     $args->{limit} = $limit if $limit;
1224     $args->{offset} = $offset if $offset;
1225
1226     if (my $max_age = $self->ctx->{get_org_setting}->(
1227         $e->requestor->home_ou, "opac.payment_history_age_limit"
1228     )) {
1229         my $min_ts = DateTime->now(
1230             "time_zone" => DateTime::TimeZone->new("name" => "local"),
1231         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
1232         
1233         $logger->info("XXX min_ts: $min_ts");
1234         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
1235     }
1236
1237     $self->ctx->{payments} = $U->simplereq(
1238         'open-ils.actor',
1239         'open-ils.actor.user.payments.retrieve.atomic',
1240         $e->authtoken, $e->requestor->id, $args);
1241
1242     return Apache2::Const::OK;
1243 }
1244
1245 # 1. caches the form parameters
1246 # 2. loads the credit card payment "Processing..." page
1247 sub load_myopac_pay_init {
1248     my $self = shift;
1249     my $cache = OpenSRF::Utils::Cache->new('global');
1250
1251     my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
1252
1253     if (!@payment_xacts) {
1254         # for consistency with load_myopac_payment_form() and
1255         # to preserve backwards compatibility, if no xacts are
1256         # selected, assume all (applicable) transactions are wanted.
1257         my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
1258         return $stat if $stat;
1259         @payment_xacts =
1260             map { $_->{xact}->id } (
1261                 @{$self->ctx->{fines}->{circulation}}, 
1262                 @{$self->ctx->{fines}->{grocery}}
1263         );
1264     }
1265
1266     return $self->generic_redirect unless @payment_xacts;
1267
1268     my $cc_args = {"where_process" => 1};
1269
1270     $cc_args->{$_} = $self->cgi->param($_) for (qw/
1271         number cvv2 expire_year expire_month billing_first
1272         billing_last billing_address billing_city billing_state
1273         billing_zip
1274     /);
1275
1276     my $cache_args = {
1277         cc_args => $cc_args, 
1278         user => $self->ctx->{user}->id,
1279         xacts => \@payment_xacts
1280     };
1281
1282     # generate a temporary cache token and cache the form data
1283     my $token = md5_hex($$ . time() . rand());
1284     $cache->put_cache($token, $cache_args, 30);
1285
1286     $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
1287
1288     # after we render the processing page, we quickly redirect to submit
1289     # the actual payment.  The refresh url contains the payment token.
1290     # It also contains the list of xact IDs, which allows us to clear the 
1291     # cache at the earliest possible time while leaving a trace of which 
1292     # transactions we were processing, so the UI can bring the user back
1293     # to the payment form w/ the same xacts if the payment fails.
1294
1295     my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
1296     $refresh .= ";xact=$_" for @payment_xacts;
1297     $self->ctx->{refresh} = $refresh;
1298
1299     return Apache2::Const::OK;
1300 }
1301
1302 # retrieve the cached CC payment info and send off for processing
1303 sub load_myopac_pay {
1304     my $self = shift;
1305     my $token = $self->ctx->{page_args}->[0];
1306     return Apache2::Const::HTTP_BAD_REQUEST unless $token;
1307
1308     my $cache = OpenSRF::Utils::Cache->new('global');
1309     my $cache_args = $cache->get_cache($token);
1310     $cache->delete_cache($token);
1311
1312     # this page is loaded immediately after the token is created.
1313     # if the cached data is not there, it's because of an invalid
1314     # token (or cache failure) and not because of a timeout.
1315     return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
1316
1317     my @payment_xacts = @{$cache_args->{xacts}};
1318     my $cc_args = $cache_args->{cc_args};
1319
1320     # as an added security check, verify the user submitting 
1321     # the form is the same as the user whose data was cached
1322     return Apache2::Const::HTTP_BAD_REQUEST unless
1323         $cache_args->{user} == $self->ctx->{user}->id;
1324
1325     $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
1326
1327     my $r;
1328     $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
1329
1330     # balance_owed is computed specifically from the fines we're paying
1331     if ($self->ctx->{fines}->{balance_owed} <= 0) {
1332         $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
1333         return Apache2::Const::HTTP_BAD_REQUEST;
1334     }
1335
1336     my $args = {
1337         "cc_args" => $cc_args,
1338         "userid" => $self->ctx->{user}->id,
1339         "payment_type" => "credit_card_payment",
1340         "payments" => $self->prepare_fines_for_payment  # should be safe after self->prepare_fines
1341     };
1342
1343     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
1344         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
1345     );
1346
1347     $self->ctx->{"payment_response"} = $resp;
1348
1349     unless ($resp->{"textcode"}) {
1350         $self->ctx->{printable_receipt} = $U->simplereq(
1351            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1352            $self->editor->authtoken, $resp->{payments}
1353         );
1354     }
1355
1356     return Apache2::Const::OK;
1357 }
1358
1359 sub load_myopac_receipt_print {
1360     my $self = shift;
1361
1362     $self->ctx->{printable_receipt} = $U->simplereq(
1363        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
1364        $self->editor->authtoken, [$self->cgi->param("payment")]
1365     );
1366
1367     return Apache2::Const::OK;
1368 }
1369
1370 sub load_myopac_receipt_email {
1371     my $self = shift;
1372
1373     # The following ML method doesn't actually check whether the user in
1374     # question has an email address, so we do.
1375     if ($self->ctx->{user}->email) {
1376         $self->ctx->{email_receipt_result} = $U->simplereq(
1377            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
1378            $self->editor->authtoken, [$self->cgi->param("payment")]
1379         );
1380     } else {
1381         $self->ctx->{email_receipt_result} =
1382             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
1383     }
1384
1385     return Apache2::Const::OK;
1386 }
1387
1388 sub prepare_fines {
1389     my ($self, $limit, $offset, $id_list) = @_;
1390
1391     # XXX TODO: check for failure after various network calls
1392
1393     # It may be unclear, but this result structure lumps circulation and
1394     # reservation fines together, and keeps grocery fines separate.
1395     $self->ctx->{"fines"} = {
1396         "circulation" => [],
1397         "grocery" => [],
1398         "total_paid" => 0,
1399         "total_owed" => 0,
1400         "balance_owed" => 0
1401     };
1402
1403     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1404
1405     # TODO: This should really be a ML call, but the existing calls 
1406     # return an excessive amount of data and don't offer streaming
1407
1408     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
1409
1410     my $req = $cstore->request(
1411         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
1412         {
1413             usr => $self->editor->requestor->id,
1414             balance_owed => {'!=' => 0},
1415             ($id_list && @$id_list ? ("id" => $id_list) : ()),
1416         },
1417         {
1418             flesh => 4,
1419             flesh_fields => {
1420                 mobts => [qw/grocery circulation reservation/],
1421                 bresv => ['target_resource_type'],
1422                 brt => ['record'],
1423                 mg => ['billings'],
1424                 mb => ['btype'],
1425                 circ => ['target_copy'],
1426                 acp => ['call_number'],
1427                 acn => ['record']
1428             },
1429             order_by => { mobts => 'xact_start' },
1430             %paging
1431         }
1432     );
1433
1434     my @total_keys = qw/total_paid total_owed balance_owed/;
1435     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
1436
1437     while(my $resp = $req->recv) {
1438         my $mobts = $resp->content;
1439         my $circ = $mobts->circulation;
1440
1441         my $last_billing;
1442         if($mobts->grocery) {
1443             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
1444             $last_billing = pop(@billings);
1445         }
1446
1447         # XXX TODO confirm that the following, and the later division by 100.0
1448         # to get a floating point representation once again, is sufficiently
1449         # "money-safe" math.
1450         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
1451
1452         my $marc_xml = undef;
1453         if ($mobts->xact_type eq 'reservation' and
1454             $mobts->reservation->target_resource_type->record) {
1455             $marc_xml = XML::LibXML->new->parse_string(
1456                 $mobts->reservation->target_resource_type->record->marc
1457             );
1458         } elsif ($mobts->xact_type eq 'circulation' and
1459             $circ->target_copy->call_number->id != -1) {
1460             $marc_xml = XML::LibXML->new->parse_string(
1461                 $circ->target_copy->call_number->record->marc
1462             );
1463         }
1464
1465         push(
1466             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
1467             {
1468                 xact => $mobts,
1469                 last_grocery_billing => $last_billing,
1470                 marc_xml => $marc_xml
1471             } 
1472         );
1473     }
1474
1475     $cstore->kill_me;
1476
1477     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
1478     return;
1479 }
1480
1481 sub prepare_fines_for_payment {
1482     # This assumes $self->prepare_fines has already been run
1483     my ($self) = @_;
1484
1485     my @results = ();
1486     if ($self->ctx->{fines}) {
1487         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
1488             @{$self->ctx->{fines}->{circulation}},
1489             @{$self->ctx->{fines}->{grocery}}
1490         );
1491     }
1492
1493     return \@results;
1494 }
1495
1496 sub load_myopac_main {
1497     my $self = shift;
1498     my $limit = $self->cgi->param('limit') || 0;
1499     my $offset = $self->cgi->param('offset') || 0;
1500     $self->ctx->{search_ou} = $self->_get_search_lib();
1501     $self->ctx->{user}->notes(
1502         $self->editor->search_actor_usr_note({
1503             usr => $self->ctx->{user}->id,
1504             pub => 't'
1505         })
1506     );
1507     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1508 }
1509
1510 sub load_myopac_update_email {
1511     my $self = shift;
1512     my $e = $self->editor;
1513     my $ctx = $self->ctx;
1514     my $email = $self->cgi->param('email') || '';
1515     my $current_pw = $self->cgi->param('current_pw') || '';
1516
1517     # needed for most up-to-date email address
1518     if (my $r = $self->prepare_extended_user_info) { return $r };
1519
1520     return Apache2::Const::OK 
1521         unless $self->cgi->request_method eq 'POST';
1522
1523     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1524         $ctx->{invalid_email} = $email;
1525         return Apache2::Const::OK;
1526     }
1527
1528     my $stat = $U->simplereq(
1529         'open-ils.actor', 
1530         'open-ils.actor.user.email.update', 
1531         $e->authtoken, $email, $current_pw);
1532
1533     if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
1534         $ctx->{password_incorrect} = 1;
1535         return Apache2::Const::OK;
1536     }
1537
1538     unless ($self->cgi->param("redirect_to")) {
1539         my $url = $self->apache->unparsed_uri;
1540         $url =~ s/update_email/prefs/;
1541
1542         return $self->generic_redirect($url);
1543     }
1544
1545     return $self->generic_redirect;
1546 }
1547
1548 sub load_myopac_update_username {
1549     my $self = shift;
1550     my $e = $self->editor;
1551     my $ctx = $self->ctx;
1552     my $username = $self->cgi->param('username') || '';
1553     my $current_pw = $self->cgi->param('current_pw') || '';
1554
1555     $self->prepare_extended_user_info;
1556
1557     my $allow_change = 1;
1558     my $regex_check;
1559     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
1560     if(defined($lock_usernames) and $lock_usernames == 1) {
1561         # Policy says no username changes
1562         $allow_change = 0;
1563     } else {
1564         # We want this further down.
1565         $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
1566         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
1567         if(!$username_unlimit) {
1568             if(!$regex_check) {
1569                 # Default is "starts with a number"
1570                 $regex_check = '^\d+';
1571             }
1572             # You already have a username?
1573             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
1574                 $allow_change = 0;
1575             }
1576         }
1577     }
1578     if(!$allow_change) {
1579         my $url = $self->apache->unparsed_uri;
1580         $url =~ s/update_username/prefs/;
1581
1582         return $self->generic_redirect($url);
1583     }
1584
1585     return Apache2::Const::OK 
1586         unless $self->cgi->request_method eq 'POST';
1587
1588     unless($username and $username !~ /\s/) { # any other username restrictions?
1589         $ctx->{invalid_username} = $username;
1590         return Apache2::Const::OK;
1591     }
1592
1593     # New username can't look like a barcode if we have a barcode regex
1594     if($regex_check and $username =~ /$regex_check/) {
1595         $ctx->{invalid_username} = $username;
1596         return Apache2::Const::OK;
1597     }
1598
1599     # New username has to look like a username if we have a username regex
1600     $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
1601     if($regex_check and $username !~ /$regex_check/) {
1602         $ctx->{invalid_username} = $username;
1603         return Apache2::Const::OK;
1604     }
1605
1606     if($username ne $e->requestor->usrname) {
1607
1608         my $evt = $U->simplereq(
1609             'open-ils.actor', 
1610             'open-ils.actor.user.username.update', 
1611             $e->authtoken, $username, $current_pw);
1612
1613         if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1614             $ctx->{password_incorrect} = 1;
1615             return Apache2::Const::OK;
1616         }
1617
1618         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1619             $ctx->{username_exists} = $username;
1620             return Apache2::Const::OK;
1621         }
1622     }
1623
1624     my $url = $self->apache->unparsed_uri;
1625     $url =~ s/update_username/prefs/;
1626
1627     return $self->generic_redirect($url);
1628 }
1629
1630 sub load_myopac_update_password {
1631     my $self = shift;
1632     my $e = $self->editor;
1633     my $ctx = $self->ctx;
1634
1635     return Apache2::Const::OK 
1636         unless $self->cgi->request_method eq 'POST';
1637
1638     my $current_pw = $self->cgi->param('current_pw') || '';
1639     my $new_pw = $self->cgi->param('new_pw') || '';
1640     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1641
1642     unless($new_pw eq $new_pw2) {
1643         $ctx->{password_nomatch} = 1;
1644         return Apache2::Const::OK;
1645     }
1646
1647     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1648
1649     if(!$pw_regex) {
1650         # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
1651         $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
1652     }
1653
1654     if($pw_regex and $new_pw !~ /$pw_regex/) {
1655         $ctx->{password_invalid} = 1;
1656         return Apache2::Const::OK;
1657     }
1658
1659     my $evt = $U->simplereq(
1660         'open-ils.actor', 
1661         'open-ils.actor.user.password.update', 
1662         $e->authtoken, $new_pw, $current_pw);
1663
1664
1665     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1666         $ctx->{password_incorrect} = 1;
1667         return Apache2::Const::OK;
1668     }
1669
1670     my $url = $self->apache->unparsed_uri;
1671     $url =~ s/update_password/prefs/;
1672
1673     return $self->generic_redirect($url);
1674 }
1675
1676 sub _update_bookbag_metadata {
1677     my ($self, $bookbag) = @_;
1678
1679     $bookbag->name($self->cgi->param("name"));
1680     $bookbag->description($self->cgi->param("description"));
1681
1682     return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
1683     return 0;
1684 }
1685
1686 sub load_myopac_bookbags {
1687     my $self = shift;
1688     my $e = $self->editor;
1689     my $ctx = $self->ctx;
1690     my $limit = $self->cgi->param('limit') || 10;
1691     my $offset = $self->cgi->param('offset') || 0;
1692
1693     $ctx->{bookbags_limit} = $limit;
1694     $ctx->{bookbags_offset} = $offset;
1695
1696     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
1697     $e->xact_begin; # replication...
1698
1699     my $rv = $self->load_mylist;
1700     unless($rv eq Apache2::Const::OK) {
1701         $e->rollback;
1702         return $rv;
1703     }
1704
1705     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
1706         [
1707             {owner => $e->requestor->id, btype => 'bookbag'}, {
1708                 order_by => {cbreb => 'name'},
1709                 limit => $limit,
1710                 offset => $offset
1711             }
1712         ],
1713         {substream => 1}
1714     );
1715
1716     if(!$ctx->{bookbags}) {
1717         $e->rollback;
1718         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1719     }
1720
1721     # We load the user prefs to get their default bookbag.
1722     $self->_load_user_with_prefs;
1723
1724     # We also want a total count of the user's bookbags.
1725     my $q = {
1726         'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
1727         'from' => 'cbreb',
1728         'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
1729     };
1730     my $r = $e->json_query($q);
1731     $ctx->{bookbag_count} = $r->[0]->{'count'};
1732
1733     # If the user wants a specific bookbag's items, load them.
1734     # XXX add bookbag item paging support
1735
1736     if ($self->cgi->param("bbid")) {
1737         my ($bookbag) =
1738             grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
1739
1740         if ($bookbag) {
1741             if ( ($self->cgi->param("action") || '') eq "editmeta") {
1742                 if (!$self->_update_bookbag_metadata($bookbag))  {
1743                     $e->rollback;
1744                     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1745                 } else {
1746                     $e->commit;
1747                     my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
1748                         $bookbag->id;
1749
1750                     foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
1751                         if ($self->cgi->param($param)) {
1752                             $url .= ";$param=" . uri_escape($self->cgi->param($param));
1753                         }
1754                     }
1755
1756                     return $self->generic_redirect($url);
1757                 }
1758             }
1759
1760             # we're done with our CStoreEditor.  Rollback here so 
1761             # later calls don't cause a timeout, resulting in a 
1762             # transaction rollback under the covers.
1763             $e->rollback;
1764
1765
1766             my $query = $self->_prepare_bookbag_container_query(
1767                 $bookbag->id, $sorter, $modifier
1768             );
1769
1770             # XXX Limiting to 1000 for now.  This way you should be able to see entire
1771             # list contents.  Need to add paging here instead.
1772             my $args = {
1773                 "limit" => 1000,
1774                 "offset" => 0
1775             };
1776
1777             my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
1778                 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1779
1780             # capture pref_ou for callnumber filter/display
1781             $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
1782
1783             # search for local callnumbers for display
1784             my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
1785
1786             my (undef, @recs) = $self->get_records_and_facets(
1787                 [ map {$_->target_biblio_record_entry->id} @$items ],
1788                 undef, 
1789                 {
1790                     flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
1791                     flesh_depth => 1,
1792                     site => $ctx->{get_aou}->($focus_ou)->shortname,
1793                     pref_lib => $ctx->{pref_ou}
1794                 }
1795             );
1796
1797             $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
1798
1799             $bookbag->items($items);
1800         }
1801     }
1802
1803     # If we have add_rec, we got here from the "Add to new list"
1804     # or "See all" popmenu items.
1805     if (my $add_rec = $self->cgi->param('add_rec')) {
1806         $self->ctx->{add_rec} = $add_rec;
1807         # But not in the staff client, 'cause that breaks things.
1808         unless ($self->ctx->{is_staff}) {
1809             $self->ctx->{where_from} = $self->ctx->{referer};
1810             if ( my $anchor = $self->cgi->param('anchor') ) {
1811                 $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
1812             }
1813         }
1814     }
1815
1816     # this rollback may be a dupe, but that's OK because 
1817     # cstoreditor ignores dupe rollbacks
1818     $e->rollback;
1819
1820     return Apache2::Const::OK;
1821 }
1822
1823
1824 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold
1825 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1826 sub load_myopac_bookbag_update {
1827     my ($self, $action, $list_id, @hold_recs) = @_;
1828     my $e = $self->editor;
1829     my $cgi = $self->cgi;
1830
1831     # save_notes is effectively another action, but is passed in a separate
1832     # CGI parameter for what are really just layout reasons.
1833     $action = 'save_notes' if $cgi->param('save_notes');
1834     $action ||= $cgi->param('action');
1835
1836     $list_id ||= $cgi->param('list') || $cgi->param('bbid');
1837
1838     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1839     my @selected_item = $cgi->param('selected_item');
1840     my $shared = $cgi->param('shared');
1841     my $name = $cgi->param('name');
1842     my $description = $cgi->param('description');
1843     my $success = 0;
1844     my $list;
1845
1846     # This url intentionally leaves off the edit_notes parameter, but
1847     # may need to add some back in for paging.
1848
1849     my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
1850         $self->ctx->{opac_root} . "/myopac/lists?";
1851
1852     foreach my $param (('loc', 'qtype', 'query', 'sort')) {
1853         if ($cgi->param($param)) {
1854             $url .= "$param=" . uri_escape($cgi->param($param)) . ";";
1855         }
1856     }
1857
1858     if ($action eq 'create') {
1859         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1860         $list->name($name);
1861         $list->description($description);
1862         $list->owner($e->requestor->id);
1863         $list->btype('bookbag');
1864         $list->pub($shared ? 't' : 'f');
1865         $success = $U->simplereq('open-ils.actor',
1866             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
1867         if (ref($success) ne 'HASH' && scalar @add_rec) {
1868             $list_id = (ref($success)) ? $success->id : $success;
1869             foreach my $add_rec (@add_rec) {
1870                 my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1871                 $item->bucket($list_id);
1872                 $item->target_biblio_record_entry($add_rec);
1873                 $success = $U->simplereq('open-ils.actor',
1874                                          'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1875                 last unless $success;
1876             }
1877             $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
1878         }
1879     } elsif($action eq 'place_hold') {
1880
1881         # @hold_recs comes from anon lists redirect; selected_itesm comes from existing buckets
1882         unless (@hold_recs) {
1883             if (@selected_item) {
1884                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
1885                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
1886             }
1887         }
1888                 
1889         return Apache2::Const::OK unless @hold_recs;
1890         $logger->info("placing holds from list page on: @hold_recs");
1891
1892         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
1893         $url .= ';hold_target=' . $_ for @hold_recs;
1894         foreach my $param (('loc', 'qtype', 'query')) {
1895             if ($cgi->param($param)) {
1896                 $url .= ";$param=" . uri_escape($cgi->param($param));
1897             }
1898         }
1899         return $self->generic_redirect($url);
1900
1901     } else {
1902
1903         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1904
1905         return Apache2::Const::HTTP_BAD_REQUEST unless 
1906             $list and $list->owner == $e->requestor->id;
1907     }
1908
1909     if($action eq 'delete') {
1910         $success = $U->simplereq('open-ils.actor', 
1911             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1912         if ($success) {
1913             # We check to see if we're deleting the user's default list.
1914             $self->_load_user_with_prefs;
1915             my $settings_map = $self->ctx->{user_setting_map};
1916             if ($$settings_map{'opac.default_list'} == $list_id) {
1917                 # We unset the user's opac.default_list setting.
1918                 $success = $U->simplereq(
1919                     'open-ils.actor',
1920                     'open-ils.actor.patron.settings.update',
1921                     $e->authtoken,
1922                     $e->requestor->id,
1923                     { 'opac.default_list' => 0 }
1924                 );
1925             }
1926         }
1927     } elsif($action eq 'show') {
1928         unless($U->is_true($list->pub)) {
1929             $list->pub('t');
1930             $success = $U->simplereq('open-ils.actor', 
1931                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1932         }
1933
1934     } elsif($action eq 'hide') {
1935         if($U->is_true($list->pub)) {
1936             $list->pub('f');
1937             $success = $U->simplereq('open-ils.actor', 
1938                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1939         }
1940
1941     } elsif($action eq 'rename') {
1942         if($name) {
1943             $list->name($name);
1944             $success = $U->simplereq('open-ils.actor', 
1945                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1946         }
1947
1948     } elsif($action eq 'add_rec') {
1949         foreach my $add_rec (@add_rec) {
1950             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1951             $item->bucket($list_id);
1952             $item->target_biblio_record_entry($add_rec);
1953             $success = $U->simplereq('open-ils.actor', 
1954                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1955             last unless $success;
1956         }
1957         # Redirect back where we came from if we have an anchor parameter:
1958         if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
1959             $url = $self->ctx->{referer};
1960             $url =~ s/#.*|$/#$anchor/;
1961         } elsif ($cgi->param('where_from')) {
1962             # Or, if we have a "where_from" parameter.
1963             $url = $cgi->param('where_from');
1964         }
1965     } elsif ($action eq 'del_item') {
1966         foreach (@selected_item) {
1967             $success = $U->simplereq(
1968                 'open-ils.actor',
1969                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1970             );
1971             last unless $success;
1972         }
1973     } elsif ($action eq 'save_notes') {
1974         $success = $self->update_bookbag_item_notes;
1975         $url .= "&bbid=" . uri_escape($cgi->param("bbid")) if $cgi->param("bbid");
1976     } elsif ($action eq 'make_default') {
1977         $success = $U->simplereq(
1978             'open-ils.actor',
1979             'open-ils.actor.patron.settings.update',
1980             $e->authtoken,
1981             $list->owner,
1982             { 'opac.default_list' => $list_id }
1983         );
1984     } elsif ($action eq 'remove_default') {
1985         $success = $U->simplereq(
1986             'open-ils.actor',
1987             'open-ils.actor.patron.settings.update',
1988             $e->authtoken,
1989             $list->owner,
1990             { 'opac.default_list' => 0 }
1991         );
1992     }
1993
1994     return $self->generic_redirect($url) if $success;
1995
1996     # XXX FIXME Bucket failure doesn't have a page to show the user anything
1997     # right now. User just sees a 404 currently.
1998
1999     $self->ctx->{bucket_action} = $action;
2000     $self->ctx->{bucket_action_failed} = 1;
2001     return Apache2::Const::OK;
2002 }
2003
2004 sub update_bookbag_item_notes {
2005     my ($self) = @_;
2006     my $e = $self->editor;
2007
2008     my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
2009     my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
2010
2011     # We're going to leverage an API call that's already been written to check
2012     # permissions appropriately.
2013
2014     my $a = create OpenSRF::AppSession("open-ils.actor");
2015     my $method = "open-ils.actor.container.item_note.cud";
2016
2017     for my $note_key (@note_keys) {
2018         my $note;
2019
2020         my $id = ($note_key =~ /(\d+)/)[0];
2021
2022         if (!($note =
2023             $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
2024             my $event = $e->die_event;
2025             $self->apache->log->warn(
2026                 "error retrieving cbrebin id $id, got event " .
2027                 $event->{textcode}
2028             );
2029             $a->kill_me;
2030             $self->ctx->{bucket_action_event} = $event;
2031             return;
2032         }
2033
2034         if (length($self->cgi->param($note_key))) {
2035             $note->ischanged(1);
2036             $note->note($self->cgi->param($note_key));
2037         } else {
2038             $note->isdeleted(1);
2039         }
2040
2041         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2042
2043         if (defined $U->event_code($r)) {
2044             $self->apache->log->warn(
2045                 "attempt to modify cbrebin " . $note->id .
2046                 " returned event " .  $r->{textcode}
2047             );
2048             $e->rollback;
2049             $a->kill_me;
2050             $self->ctx->{bucket_action_event} = $r;
2051             return;
2052         }
2053     }
2054
2055     for my $item_key (@item_keys) {
2056         my $id = int(($item_key =~ /(\d+)/)[0]);
2057         my $text = $self->cgi->param($item_key);
2058
2059         chomp $text;
2060         next unless length $text;
2061
2062         my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
2063         $note->isnew(1);
2064         $note->item($id);
2065         $note->note($text);
2066
2067         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
2068
2069         if (defined $U->event_code($r)) {
2070             $self->apache->log->warn(
2071                 "attempt to create cbrebin for item " . $note->item .
2072                 " returned event " .  $r->{textcode}
2073             );
2074             $e->rollback;
2075             $a->kill_me;
2076             $self->ctx->{bucket_action_event} = $r;
2077             return;
2078         }
2079     }
2080
2081     $a->kill_me;
2082     return 1;   # success
2083 }
2084
2085 sub load_myopac_bookbag_print {
2086     my ($self) = @_;
2087
2088     my $id = int($self->cgi->param("list"));
2089
2090     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2091
2092     my $item_search =
2093         $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
2094
2095     my $bbag;
2096
2097     # Get the bookbag object itself, assuming we're allowed to.
2098     if ($self->editor->allowed("VIEW_CONTAINER")) {
2099
2100         $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2101     } else {
2102         my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
2103             {
2104                 "id" => $id,
2105                 "-or" => {
2106                     "owner" => $self->editor->requestor->id,
2107                     "pub" => "t"
2108                 }
2109             }
2110         ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2111
2112         $bbag = pop @$bookbags;
2113     }
2114
2115     # If we have a bookbag we're allowed to look at, issue the A/T event
2116     # to get CSV, passing as a user param that search query we built before.
2117     if ($bbag) {
2118         $self->ctx->{csv} = $U->fire_object_event(
2119             undef, "container.biblio_record_entry_bucket.csv",
2120             $bbag, $self->editor->requestor->home_ou,
2121             undef, {"item_search" => $item_search}
2122         );
2123     }
2124
2125     # Create a reasonable filename and set the content disposition to
2126     # provoke browser download dialogs.
2127     (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
2128
2129     return $self->set_file_download_headers("$filename.csv");
2130 }
2131
2132 sub load_myopac_circ_history_export {
2133     my $self = shift;
2134     my $e = $self->editor;
2135     my $filename = $self->cgi->param('filename') || 'circ_history.csv';
2136
2137     my $ids = $e->json_query({
2138         select => {
2139             au => [{
2140                 column => 'id', 
2141                 transform => 'action.usr_visible_circs', 
2142                 result_field => 'id'
2143             }]
2144         },
2145         from => 'au',
2146         where => {id => $e->requestor->id} 
2147     });
2148
2149     $self->ctx->{csv} = $U->fire_object_event(
2150         undef, 
2151         'circ.format.history.csv',
2152         $e->search_action_circulation({id => [map {$_->{id}} @$ids]}, {substream =>1}),
2153         $self->editor->requestor->home_ou
2154     );
2155
2156     return $self->set_file_download_headers($filename);
2157 }
2158
2159 sub load_password_reset {
2160     my $self = shift;
2161     my $cgi = $self->cgi;
2162     my $ctx = $self->ctx;
2163     my $barcode = $cgi->param('barcode');
2164     my $username = $cgi->param('username');
2165     my $email = $cgi->param('email');
2166     my $pwd1 = $cgi->param('pwd1');
2167     my $pwd2 = $cgi->param('pwd2');
2168     my $uuid = $ctx->{page_args}->[0];
2169
2170     if ($uuid) {
2171
2172         $logger->info("patron password reset with uuid $uuid");
2173
2174         if ($pwd1 and $pwd2) {
2175
2176             if ($pwd1 eq $pwd2) {
2177
2178                 my $response = $U->simplereq(
2179                     'open-ils.actor', 
2180                     'open-ils.actor.patron.password_reset.commit',
2181                     $uuid, $pwd1);
2182
2183                 $logger->info("patron password reset response " . Dumper($response));
2184
2185                 if ($U->event_code($response)) { # non-success event
2186                     
2187                     my $code = $response->{textcode};
2188                     
2189                     if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
2190                         $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
2191                     }
2192
2193                     if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
2194                         $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
2195                     }
2196
2197                 } else { # success
2198
2199                     $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
2200                 }
2201
2202             } else { # passwords not equal
2203
2204                 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
2205             }
2206
2207         } else { # 2 password values needed
2208
2209             $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
2210         }
2211
2212     } elsif ($barcode or $username) {
2213
2214         my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
2215         push(@params, $email) if $email;
2216
2217         $U->simplereq(
2218             'open-ils.actor', 
2219             'open-ils.actor.patron.password_reset.request', @params);
2220
2221         $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
2222     }
2223
2224     $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
2225     return Apache2::Const::OK;
2226 }
2227
2228 1;