]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
LP#1642000 - Add Call number prefix, suffix and part to opac circ history
[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 OpenSRF::EX qw/:try/;
9 use OpenILS::Event;
10 use OpenSRF::Utils::JSON;
11 use OpenSRF::Utils::Cache;
12 use OpenILS::Utils::DateTime qw/:datetime/;
13 use Digest::MD5 qw(md5_hex);
14 use Business::Stripe;
15 use Data::Dumper;
16 $Data::Dumper::Indent = 0;
17 use DateTime;
18 use DateTime::Format::ISO8601;
19 my $U = 'OpenILS::Application::AppUtils';
20 use List::MoreUtils qw/uniq/;
21
22 sub prepare_extended_user_info {
23     my $self = shift;
24     my @extra_flesh = @_;
25     my $e = $self->editor;
26
27     # are we already in a transaction?
28     my $local_xact = !$e->{xact_id};
29     $e->xact_begin if $local_xact;
30
31     # keep the original user object so we can restore
32     # login-specific data (e.g. workstation)
33     my $usr = $self->ctx->{user};
34
35     $self->ctx->{user} = $self->editor->retrieve_actor_user([
36         $self->ctx->{user}->id,
37         {
38             flesh => 2,
39             flesh_fields => {
40                 au => [qw/card home_ou addresses ident_type billing_address waiver_entries/, @extra_flesh],
41                 "aou" => ["billing_address"]
42             }
43         }
44     ]);
45
46     $e->rollback if $local_xact;
47
48     $self->ctx->{user}->wsid($usr->wsid);
49     $self->ctx->{user}->ws_ou($usr->ws_ou);
50
51     # discard replaced (negative-id) addresses.
52     $self->ctx->{user}->addresses([
53         grep {$_->id > 0} @{$self->ctx->{user}->addresses} ]);
54
55     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR
56         unless $self->ctx->{user};
57
58     return;
59 }
60
61 # Given an event returned by a failed attempt to create a hold, do we have
62 # permission to override?  XXX Should the permission check be scoped to a
63 # given org_unit context?
64 sub test_could_override {
65     my ($self, $event) = @_;
66
67     return 0 unless $event;
68     return 1 if $self->editor->allowed($event->{textcode} . ".override");
69     return 1 if $event->{"fail_part"} and
70         $self->editor->allowed($event->{"fail_part"} . ".override");
71     return 0;
72 }
73
74 # Find out whether we care that local copies are available
75 sub local_avail_concern {
76     my ($self, $hold_target, $hold_type, $pickup_lib) = @_;
77
78     my $would_block = $self->ctx->{get_org_setting}->
79         ($pickup_lib, "circ.holds.hold_has_copy_at.block");
80     my $would_alert = (
81         $self->ctx->{get_org_setting}->
82             ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
83                 not $self->cgi->param("override")
84     ) unless $would_block;
85
86     if ($would_block or $would_alert) {
87         my $args = {
88             "hold_target" => $hold_target,
89             "hold_type" => $hold_type,
90             "org_unit" => $pickup_lib
91         };
92         my $local_avail = $U->simplereq(
93             "open-ils.circ",
94             "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
95         );
96         $logger->info(
97             "copy availability information for " . Dumper($args) .
98             " is " . Dumper($local_avail)
99         );
100         if (%$local_avail) { # if hash not empty
101             $self->ctx->{hold_copy_available} = $local_avail;
102             return ($would_block, $would_alert);
103         }
104     }
105
106     return (0, 0);
107 }
108
109 # context additions:
110 #   user : au object, fleshed
111 sub load_myopac_prefs {
112     my $self = shift;
113     my $cgi = $self->cgi;
114     my $e = $self->editor;
115     my $pending_addr = $cgi->param('pending_addr');
116     my $replace_addr = $cgi->param('replace_addr');
117     my $delete_pending = $cgi->param('delete_pending');
118
119     $self->prepare_extended_user_info;
120     my $user = $self->ctx->{user};
121
122     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
123     if(defined($lock_usernames) and $lock_usernames == 1) {
124         # Policy says no username changes
125         $self->ctx->{username_change_disallowed} = 1;
126     } else {
127         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
128         if(!$username_unlimit) {
129             my $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
130             if(!$regex_check) {
131                 # Default is "starts with a number"
132                 $regex_check = '^\d+';
133             }
134             # You already have a username?
135             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
136                 $self->ctx->{username_change_disallowed} = 1;
137             }
138         }
139     }
140
141     return Apache2::Const::OK unless
142         $pending_addr or $replace_addr or $delete_pending;
143
144     my @form_fields = qw/address_type street1 street2 city county state country post_code/;
145
146     my $paddr;
147     if( $pending_addr ) { # update an existing pending address
148
149         ($paddr) = grep { $_->id == $pending_addr } @{$user->addresses};
150         return Apache2::Const::HTTP_BAD_REQUEST unless $paddr;
151         $paddr->$_( $cgi->param($_) ) for @form_fields;
152
153     } elsif( $replace_addr ) { # create a new pending address for 'replace_addr'
154
155         $paddr = Fieldmapper::actor::user_address->new;
156         $paddr->isnew(1);
157         $paddr->usr($user->id);
158         $paddr->pending('t');
159         $paddr->replaces($replace_addr);
160         $paddr->$_( $cgi->param($_) ) for @form_fields;
161
162     } elsif( $delete_pending ) {
163         $paddr = $e->retrieve_actor_user_address($delete_pending);
164         return Apache2::Const::HTTP_BAD_REQUEST unless
165             $paddr and $paddr->usr == $user->id and $U->is_true($paddr->pending);
166         $paddr->isdeleted(1);
167     }
168
169     my $resp = $U->simplereq(
170         'open-ils.actor',
171         'open-ils.actor.user.address.pending.cud',
172         $e->authtoken, $paddr);
173
174     if( $U->event_code($resp) ) {
175         $logger->error("Error updating pending address: $resp");
176         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
177     }
178
179     # in light of these changes, re-fetch latest data
180     $e->xact_begin;
181     $self->prepare_extended_user_info;
182     $e->rollback;
183
184     return Apache2::Const::OK;
185 }
186
187 sub load_myopac_prefs_notify {
188     my $self = shift;
189     my $e = $self->editor;
190
191
192     my $stat = $self->_load_user_with_prefs;
193     return $stat if $stat;
194
195     my $user_prefs = $self->fetch_optin_prefs;
196     $user_prefs = $self->update_optin_prefs($user_prefs)
197         if $self->cgi->request_method eq 'POST';
198
199     $self->ctx->{opt_in_settings} = $user_prefs;
200
201     return Apache2::Const::OK
202         unless $self->cgi->request_method eq 'POST';
203
204     my %settings;
205     my $set_map = $self->ctx->{user_setting_map};
206
207     foreach my $key (qw/
208         opac.default_phone
209         opac.default_sms_notify
210     /) {
211         my $val = $self->cgi->param($key);
212         $settings{$key}= $val unless $$set_map{$key} eq $val;
213     }
214
215     my $key = 'opac.default_sms_carrier';
216     my $val = $self->cgi->param('sms_carrier');
217     $settings{$key}= $val unless $$set_map{$key} eq $val;
218
219     $key = 'opac.hold_notify';
220     my @notify_methods = ();
221     if ($self->cgi->param($key . ".email") eq 'on') {
222         push @notify_methods, "email";
223     }
224     if ($self->cgi->param($key . ".phone") eq 'on') {
225         push @notify_methods, "phone";
226     }
227     if ($self->cgi->param($key . ".sms") eq 'on') {
228         push @notify_methods, "sms";
229     }
230     $val = join("|",@notify_methods);
231     $settings{$key}= $val unless $$set_map{$key} eq $val;
232
233     # Send the modified settings off to be saved
234     $U->simplereq(
235         'open-ils.actor',
236         'open-ils.actor.patron.settings.update',
237         $self->editor->authtoken, undef, \%settings);
238
239     # re-fetch user prefs
240     $self->ctx->{updated_user_settings} = \%settings;
241
242     # update holds: check if any changes affect any holds
243     my @llchgs = $self->_parse_prefs_notify_hold_related();
244     my @ffectedChgs;
245
246     if ( $self->cgi->param('hasHoldsChanges') ) {
247         # propagate pref_notify changes to holds
248         for my $chset (@llchgs){
249             # FIXME is this still needed?
250         }
251     
252     }
253     else {
254         my $holds = $U->simplereq('open-ils.circ', 'open-ils.circ.holds.retrieve.by_usr.with_notify',
255             $e->authtoken, $e->requestor->id);
256
257         if (@$holds > 0) {
258
259             my $default_phone_changes = {};
260             my $sms_changes           = {};
261             my $new_phone;
262             my $new_carrier;
263             my $new_sms;
264             for my $chset (@llchgs) {
265                 next if scalar(@$chset) < 3;
266                 my ($old, $new, $field) = @$chset;
267
268                 my $bool = $field =~ /_notify/ ? 1 : 0;
269
270                 # find holds that would change
271                 my $affected = [];
272                 foreach my $hold (@$holds) {
273                     if ($field eq 'email_notify') {
274                         my $curr = $hold->{$field} eq 't' ? 'true' : 'false';
275                         push @$affected, $hold if $curr ne $new;
276                     } elsif ($field eq 'default_phone') {
277                         my $old_phone = $hold->{phone_notify} // '';
278                         $new_phone = $new // '';
279                         push @{ $default_phone_changes->{ $old_phone } }, $hold->{id}
280                             if $old_phone ne $new_phone;
281                     } elsif ($field eq 'phone_notify') {
282                         my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
283                         push @$affected, $hold if $curr ne $new;
284                     } elsif ($field eq 'sms_notify') {
285                         my $curr = ($hold->{$field} // '' ne '') ? 'true' : 'false';
286                         push @$affected, $hold if $curr ne $new;
287                     } elsif ($field eq 'sms_info') {
288                         my $old_carrier = $hold->{'sms_carrier'} // '';
289                         my $old_sms = $hold->{'sms_notify'} // '';
290                         $new_carrier = $new->{carrier} // '';
291                         $new_sms = $new->{sms} // '';
292                         if (!($old_carrier eq $new_carrier && $old_sms eq $new_sms)) {
293                             push @{ $sms_changes->{ join("\t", $old_carrier, $old_sms) } }, $hold->{id};
294                         }
295                     }
296                 }
297
298                 # append affected array to chset
299                 if (scalar(@$affected) > 0){
300                     push(@$chset, [ map { $_->{id} } @$affected ]);
301                     push(@ffectedChgs, $chset);
302                 }
303             }
304
305
306             foreach my $old_phone (keys %$default_phone_changes) {
307                 push(@ffectedChgs, [ $old_phone, $new_phone, 'default_phone', $default_phone_changes->{$old_phone} ]);
308             }
309             foreach my $old_sms_info (keys %$sms_changes) {
310                 my ($old_carrier, $old_sms) = split /\t/, $old_sms_info;
311                 push(@ffectedChgs, [
312                                         { carrier => $old_carrier, sms => $old_sms },
313                                         { carrier => $new_carrier, sms => $new_sms },
314                                         'sms_info',
315                                         $sms_changes->{$old_sms_info}
316                                    ]);
317             }
318
319             if ( scalar(@ffectedChgs) ){
320                 $self->ctx->{affectedChgs} = \@ffectedChgs;
321             }
322         }
323     }
324
325     return $self->_load_user_with_prefs || Apache2::Const::OK;
326 }
327
328 sub _parse_prefs_notify_hold_related {
329
330     my $self = shift;
331     my $for_update = shift;
332
333     # create an array of change arrays
334     my @chgs;
335
336     my @phone_notify = $self->cgi->multi_param('phone_notify[]');
337     push(@chgs, \@phone_notify) if scalar(@phone_notify);
338
339     my $turning_on_phone_notify  = !$for_update &&
340                                    scalar(@phone_notify) &&
341                                    $phone_notify[1] eq 'true';
342     my $turning_off_phone_notify = !$for_update &&
343                                    scalar(@phone_notify) &&
344                                    $phone_notify[1] eq 'false';
345
346     my $changing_default_phone = 0;
347     if (!$turning_off_phone_notify) {
348         my @default_phone = $self->cgi->multi_param('default_phone[]');
349         if ($for_update) {
350             while (scalar(@default_phone) > 0) {
351                 my $chg = [ splice(@default_phone, 0, 4) ];
352                 if (scalar(@default_phone) > 0 && $default_phone[0] eq 'on') {
353                     push @$chg, shift(@default_phone);
354                     push(@chgs, $chg);
355                     $changing_default_phone = 1;
356                 }
357             }
358         } else {
359             if (scalar(@default_phone)) {
360                 push @chgs, \@default_phone;
361                 $changing_default_phone = 1;
362             }
363         }
364     }
365
366     if ($turning_on_phone_notify && $changing_default_phone) {
367         # we don't need to have both the phone_notify and default_phone
368         # changes; the latter will suffice
369         @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
370     } elsif ($turning_on_phone_notify && !$changing_default_phone) {
371         # replace the phone_notify change with a default_phone change
372         @chgs = grep { $_->[2] ne 'phone_notify' } @chgs;
373         my $default_phone = $self->cgi->param('opac.default_phone'); # we assume this is set
374         push @chgs, [ '', $default_phone, 'default_phone' ];
375     }
376
377     # on to SMS
378     # ... since both carrier and number are needed to send an SMS notifcation,
379     # we need to treat the pair as a unit
380     my @sms_notify = $self->cgi->multi_param('sms_notify[]');
381     push(@chgs, \@sms_notify) if scalar(@sms_notify);
382
383     my $turning_on_sms_notify  = !$for_update &&
384                                    scalar(@sms_notify) &&
385                                    $sms_notify[1] eq 'true';
386     my $turning_off_sms_notify = !$for_update &&
387                                    scalar(@sms_notify) &&
388                                    $sms_notify[1] eq 'false';
389
390     my $changing_sms_info = 0;
391     if (!$turning_off_sms_notify) {
392         my @sms_carrier = $self->cgi->multi_param('default_sms_carrier_id[]');
393         my @sms = $self->cgi->multi_param('default_sms[]');
394
395         if (scalar(@sms) || scalar(@sms_carrier)) {
396             my $new_carrier = scalar(@sms_carrier) ? $sms_carrier[1] : $self->cgi->param('sms_carrier');
397             my $new_sms = scalar(@sms) ? $sms[1] : $self->cgi->param('opac.default_sms_notify');
398             push @chgs, [
399                             { carrier => '', sms => '' },
400                             { carrier => $new_carrier, sms => $new_sms },
401                             'sms_info'
402                         ];
403            $changing_sms_info = 1;
404         }
405     }
406
407     my @sms_info = $self->cgi->multi_param('sms_info[]'); # only sent by confirmation page
408     if (scalar(@sms_info)) {
409         while (scalar(@sms_info) > 0) {
410             my $chg = [ splice(@sms_info, 0, 4) ];
411             if (scalar(@sms_info) > 0 && $sms_info[0] eq 'on') {
412                 push @$chg, shift(@sms_info);
413                 my ($carrier, $sms) = split /,/, $chg->[0], -1;
414                 $chg->[0] = { carrier => $carrier, sms => $sms };
415                 ($carrier, $sms) = split /,/, $chg->[1], -1;
416                 $chg->[1] = { carrier => $carrier, sms => $sms };
417                 push(@chgs, $chg);
418                 $changing_sms_info = 1;
419             }
420         }
421     }
422
423     if ($turning_on_sms_notify && $changing_sms_info) {
424         # we don't need to have both the sms_notify and sms_info
425         # changes; the latter will suffice
426         @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
427     } elsif ($turning_on_sms_notify && !$changing_sms_info) {
428         # replace the sms_notify change with a sms_info change
429         @chgs = grep { $_->[2] ne 'sms_notify' } @chgs;
430         my $sms_info = {
431             carrier => $self->cgi->param('sms_carrier'),
432             sms     => $self->cgi->param('opac.default_sms_notify'),
433         };
434         push @chgs, [ { carrier => '', sms => ''}, $sms_info, 'sms_info' ];
435     }
436
437     my @email_notify = $self->cgi->multi_param('email_notify[]');
438     push(@chgs, \@email_notify) if scalar(@email_notify);
439
440     if ($for_update) {
441         # if we're updating, keep only the ones that have been
442         # explicitly checked by the user
443         @chgs = grep { scalar(@$_) == 5 && $_->[4] eq 'on' } @chgs;
444     }
445     return @chgs;
446 }
447
448 sub load_myopac_prefs_notify_changed_holds {
449     my $self = shift;
450     my $e = $self->editor;
451
452     my $hasChanges = $self->cgi->param('hasHoldsChanges');
453     
454     return $self->_load_user_with_prefs || Apache2::Const::OK unless $hasChanges;
455
456     my @ll = $self->_parse_prefs_notify_hold_related(1);
457
458     my @updates;
459     for my $chset (@ll){
460         my ($old, $new, $type, $holdids, $doit) = @$chset;
461         next if $doit ne 'on';
462         
463         # parse string list into array list
464         my @holdids = split(',', $holdids);
465         
466         if ($type =~ /_notify/){
467             # translate true/false string into 1/0
468             $old = $old eq 'true' ? 1 : 0;
469             $new = $new eq 'true' ? 1 : 0;
470         }
471
472         my $update;
473         if ($type eq 'sms_info') {
474             if ($new->{carrier} eq '' && $new->{sms} eq '') {
475                 # clear SMS number first to avoid check contrainst issue
476                 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
477                     $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
478                 push (@updates, $update) if (scalar(@$update) > 0);
479                 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
480                     $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
481                 push (@updates, $update) if (scalar(@$update) > 0);
482             } else {
483                 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
484                     $e->authtoken, $e->requestor->id, [@holdids], $old->{carrier}, $new->{carrier}, 'default_sms_carrier_id');
485                 push (@updates, $update) if (scalar(@$update) > 0);
486                 $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
487                     $e->authtoken, $e->requestor->id, [@holdids], $old->{sms}, $new->{sms}, 'default_sms');
488                 push (@updates, $update) if (scalar(@$update) > 0);
489             }
490         } else {
491             $update = $U->simplereq('open-ils.circ', "open-ils.circ.holds.batch_update_holds_by_notify",
492                 $e->authtoken, $e->requestor->id, [@holdids], $old, $new, $type);
493
494             # append affected array to chset
495             if (scalar(@$update) > 0){
496                 push(@updates, $update);
497             }
498         }
499     }
500
501     $self->ctx->{'updated'} = \@updates;
502
503     return $self->_load_user_with_prefs || Apache2::Const::OK;
504
505 }
506
507 sub fetch_optin_prefs {
508     my $self = shift;
509     my $e = $self->editor;
510
511     # fetch all of the opt-in settings the user has access to
512     # XXX: user's should in theory have options to opt-in to notices
513     # for remote locations, but that opens the door for a large
514     # set of generally un-used opt-ins.. needs discussion
515     my $opt_ins =  $U->simplereq(
516         'open-ils.actor',
517         'open-ils.actor.event_def.opt_in.settings.atomic',
518         $e->authtoken, $e->requestor->home_ou);
519
520     # some opt-ins are staff-only
521     $opt_ins = [ grep { $U->is_true($_->opac_visible) } @$opt_ins ];
522
523     # fetch user setting values for each of the opt-in settings
524     my $user_set = $U->simplereq(
525         'open-ils.actor',
526         'open-ils.actor.patron.settings.retrieve',
527         $e->authtoken,
528         $e->requestor->id,
529         [map {$_->name} @$opt_ins]
530     );
531
532     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
533 }
534
535 sub load_myopac_messages {
536     my $self = shift;
537     my $e = $self->editor;
538     my $ctx = $self->ctx;
539     my $cgi = $self->cgi;
540
541     my $limit  = $cgi->param('limit') || 20;
542     my $offset = $cgi->param('offset') || 0;
543
544     my $pcrud = OpenSRF::AppSession->create('open-ils.pcrud');
545     $pcrud->connect();
546
547     my $action = $cgi->param('action') || '';
548     if ($action) {
549         my ($changed, $failed) = $self->_handle_message_action($pcrud, $action);
550         if ($changed > 0 || $failed > 0) {
551             $ctx->{message_update_action} = $action;
552             $ctx->{message_update_changed} = $changed;
553             $ctx->{message_update_failed} = $failed;
554             $self->update_dashboard_stats();
555         }
556     }
557
558     my $single = $cgi->param('single') || 0;
559     my $id = $cgi->param('message_id');
560
561     my $messages;
562     my $fetch_all = 1;
563     if (!$action && $single && $id) {
564         $messages = $self->_fetch_and_mark_read_single_message($pcrud, $id);
565         if (scalar(@$messages) == 1) {
566             $ctx->{display_single_message} = 1;
567             $ctx->{patron_message_id} = $id;
568             $fetch_all = 0;
569         }
570     }
571
572     if ($fetch_all) {
573         # fetch all the messages
574         ($ctx->{patron_messages_count}, $messages) =
575             $self->_fetch_user_messages($pcrud, $offset, $limit);
576     }
577
578     $pcrud->kill_me;
579
580     foreach my $aum (@$messages) {
581
582         push @{ $ctx->{patron_messages} }, {
583             id          => $aum->id,
584             title       => $aum->title,
585             message     => $aum->message,
586             create_date => $aum->create_date,
587             edit_date   => $aum->edit_date,
588             is_read     => defined($aum->read_date) ? 1 : 0,
589             library     => $aum->sending_lib->name,
590         };
591     }
592
593     $ctx->{patron_messages_limit} = $limit;
594     $ctx->{patron_messages_offset} = $offset;
595
596     return Apache2::Const::OK;
597 }
598
599 sub _fetch_and_mark_read_single_message {
600     my $self = shift;
601     my $pcrud = shift;
602     my $id = shift;
603
604     $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
605     my $messages = $pcrud->request(
606         'open-ils.pcrud.search.auml.atomic',
607         $self->editor->authtoken,
608         {
609             usr     => $self->editor->requestor->id,
610             deleted => 'f',
611             id      => $id,
612         },
613         {
614             flesh => 1,
615             flesh_fields => { auml => ['sending_lib'] },
616         }
617     )->gather(1);
618     if (@$messages) {
619         $messages->[0]->read_date('now');
620         $pcrud->request(
621             'open-ils.pcrud.update.auml',
622             $self->editor->authtoken,
623             $messages->[0]
624         )->gather(1);
625     }
626     $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
627
628     $self->update_dashboard_stats();
629
630     return $messages;
631 }
632
633 sub _fetch_user_messages {
634     my $self = shift;
635     my $pcrud = shift;
636     my $offset = shift;
637     my $limit = shift;
638
639     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
640
641     my $all_messages = $pcrud->request(
642         'open-ils.pcrud.id_list.auml.atomic',
643         $self->editor->authtoken,
644         {
645             usr     => $self->editor->requestor->id,
646             deleted => 'f'
647         },
648         {}
649     )->gather(1);
650
651     my $messages = $pcrud->request(
652         'open-ils.pcrud.search.auml.atomic',
653         $self->editor->authtoken,
654         {
655             usr     => $self->editor->requestor->id,
656             deleted => 'f'
657         },
658         {
659             flesh => 1,
660             flesh_fields => { auml => ['sending_lib'] },
661             order_by => { auml => 'create_date DESC' },
662             %paging
663         }
664     )->gather(1);
665
666     return scalar(@$all_messages), $messages;
667 }
668
669 sub _handle_message_action {
670     my $self = shift;
671     my $pcrud = shift;
672     my $action = shift;
673     my $cgi = $self->cgi;
674
675     my @ids = $cgi->param('message_id');
676     return (0, 0) unless @ids;
677
678     my $changed = 0;
679     my $failed = 0;
680     $pcrud->request('open-ils.pcrud.transaction.begin', $self->editor->authtoken)->gather(1);
681     for my $id (@ids) {
682         my $aum = $pcrud->request(
683             'open-ils.pcrud.retrieve.auml',
684             $self->editor->authtoken,
685             $id
686         )->gather(1);
687         next unless $aum;
688         if      ($action eq 'mark_read') {
689             $aum->read_date('now');
690         } elsif ($action eq 'mark_unread') {
691             $aum->clear_read_date();
692         } elsif ($action eq 'mark_deleted') {
693             $aum->deleted('t');
694         }
695         $pcrud->request('open-ils.pcrud.update.auml', $self->editor->authtoken, $aum)->gather(1) ?
696             $changed++ :
697             $failed++;
698     }
699     if ($failed) {
700         $pcrud->request('open-ils.pcrud.transaction.rollback', $self->editor->authtoken)->gather(1);
701         $changed = 0;
702         $failed = scalar(@ids);
703     } else {
704         $pcrud->request('open-ils.pcrud.transaction.commit', $self->editor->authtoken)->gather(1);
705     }
706     return ($changed, $failed);
707 }
708
709 sub _load_lists_and_settings {
710     my $self = shift;
711     my $e = $self->editor;
712     my $stat = $self->_load_user_with_prefs;
713     unless ($stat) {
714         my $exclude = 0;
715         my $setting_map = $self->ctx->{user_setting_map};
716         $exclude = $$setting_map{'opac.default_list'} if ($$setting_map{'opac.default_list'});
717         $self->ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
718             [
719                 {owner => $self->ctx->{user}->id, btype => 'bookbag', id => {'<>' => $exclude}}, {
720                     order_by => {cbreb => 'name'},
721                     limit => $self->cgi->param('limit') || 10,
722                     offset => $self->cgi->param('offset') || 0
723                 }
724             ]
725         );
726         # We also want a total count of the user's bookbags.
727         my $q = {
728             'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
729             'from' => 'cbreb',
730             'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
731         };
732         my $r = $e->json_query($q);
733         $self->ctx->{bookbag_count} = $r->[0]->{'count'};
734         # Someone has requested that we use the default list's name
735         # rather than "Default List."
736         if ($exclude) {
737             $q = {
738                 'select' => {'cbreb' => ['name']},
739                 'from' => 'cbreb',
740                 'where' => {'id' => $exclude}
741             };
742             $r = $e->json_query($q);
743             $self->ctx->{default_bookbag} = $r->[0]->{'name'};
744         }
745     } else {
746         return $stat;
747     }
748     return undef;
749 }
750
751 sub update_optin_prefs {
752     my $self = shift;
753     my $user_prefs = shift;
754     my $e = $self->editor;
755     my @settings = $self->cgi->param('setting');
756     my %newsets;
757
758     # apply now-true settings
759     for my $applied (@settings) {
760         # see if setting is already applied to this user
761         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
762         $newsets{$applied} = OpenSRF::Utils::JSON->true;
763     }
764
765     # remove now-false settings
766     for my $pref (grep { $_->{value} } @$user_prefs) {
767         $newsets{$pref->{cust}->name} = undef
768             unless grep { $_ eq $pref->{cust}->name } @settings;
769     }
770
771     $U->simplereq(
772         'open-ils.actor',
773         'open-ils.actor.patron.settings.update',
774         $e->authtoken, $e->requestor->id, \%newsets);
775
776     # update the local prefs to match reality
777     for my $pref (@$user_prefs) {
778         $pref->{value} = $newsets{$pref->{cust}->name}
779             if exists $newsets{$pref->{cust}->name};
780     }
781
782     return $user_prefs;
783 }
784
785 sub _load_user_with_prefs {
786     my $self = shift;
787     my $stat = $self->prepare_extended_user_info('settings');
788     return $stat if $stat; # not-OK
789
790     $self->ctx->{user_setting_map} = {
791         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
792             @{$self->ctx->{user}->settings}
793     };
794
795     return undef;
796 }
797
798 sub _get_bookbag_sort_params {
799     my ($self, $param_name) = @_;
800
801     # The interface that feeds this cgi parameter will provide a single
802     # argument for a QP sort filter, and potentially a modifier after a period.
803     # In practice this means the "sort" parameter will be something like
804     # "titlesort" or "authorsort.descending".
805     my $sorter = $self->cgi->param($param_name) || "";
806     my $modifier;
807     if ($sorter) {
808         $sorter =~ s/^(.*?)\.(.*)/$1/;
809         $modifier = $2 || undef;
810     }
811
812     return ($sorter, $modifier);
813 }
814
815 sub _prepare_bookbag_container_query {
816     my ($self, $container_id, $sorter, $modifier) = @_;
817
818     return sprintf(
819         "container(bre,bookbag,%d,%s)%s%s",
820         $container_id, $self->editor->authtoken,
821         ($sorter ? " sort($sorter)" : ""),
822         ($modifier ? "#$modifier" : "")
823     );
824 }
825
826 sub _prepare_anonlist_sorting_query {
827     my ($self, $list, $sorter, $modifier) = @_;
828
829     return sprintf(
830         "record_list(%s)%s%s",
831         join(",", @$list),
832         ($sorter ? " sort($sorter)" : ""),
833         ($modifier ? "#$modifier" : "")
834     );
835 }
836
837
838 sub load_myopac_prefs_settings {
839     my $self = shift;
840
841     my @user_prefs = qw/
842         opac.hits_per_page
843         opac.default_search_location
844         opac.default_pickup_location
845         opac.temporary_list_no_warn
846     /;
847
848     my $stat = $self->_load_user_with_prefs;
849     return $stat if $stat;
850
851     # if behind-desk holds are supported and the user
852     # setting which controls the value is opac-visible,
853     # add the setting to the list of settings to manage.
854     # note: this logic may need to be changed later to
855     # check whether behind-the-desk holds are supported
856     # anywhere the patron may select as a pickup lib.
857     my $e = $self->editor;
858     my $bdous = $self->ctx->{get_org_setting}->(
859         $e->requestor->home_ou,
860         'circ.holds.behind_desk_pickup_supported');
861
862     if ($bdous) {
863         my $setting =
864             $e->retrieve_config_usr_setting_type(
865                 'circ.holds_behind_desk');
866
867         if ($U->is_true($setting->opac_visible)) {
868             push(@user_prefs, 'circ.holds_behind_desk');
869             $self->ctx->{behind_desk_supported} = 1;
870         }
871     }
872
873     my $use_privacy_waiver = $self->ctx->{get_org_setting}->(
874         $e->requestor->home_ou, 'circ.privacy_waiver');
875
876     return Apache2::Const::OK
877         unless $self->cgi->request_method eq 'POST';
878
879     # some setting values from the form don't match the
880     # required value/format for the db, so they have to be
881     # individually translated.
882
883     my %settings;
884     my $set_map = $self->ctx->{user_setting_map};
885
886     foreach my $key (@user_prefs) {
887         my $val = $self->cgi->param($key);
888         $settings{$key}= $val unless $$set_map{$key} eq $val;
889     }
890
891     # Used by the settings update form when warning on history delete.
892     my $clear_circ_history = 0;
893     my $clear_hold_history = 0;
894
895     # true if we need to show the warning on next page load.
896     my $hist_warning_needed = 0;
897     my $hist_clear_confirmed = $self->cgi->param('history_delete_confirmed');
898
899     my $now = DateTime->now->strftime('%F');
900     foreach my $key (
901             qw/history.circ.retention_start history.hold.retention_start/) {
902
903         my $val = $self->cgi->param($key);
904         if($val and $val eq 'on') {
905             # Set the start time to 'now' unless a start time already exists for the user
906             $settings{$key} = $now unless $$set_map{$key};
907
908         } else {
909
910             next unless $$set_map{$key}; # nothing to do
911
912             $clear_circ_history = 1 if $key =~ /circ/;
913             $clear_hold_history = 1 if $key =~ /hold/;
914
915             if (!$hist_clear_confirmed) {
916                 # when clearing circ history, only warn if history data exists.
917
918                 if ($clear_circ_history) {
919
920                     if ($self->fetch_user_circ_history(0, 1)->[0]) {
921                         $hist_warning_needed = 1;
922                         next; # no history updates while confirmation pending
923                     }
924
925                 } else {
926
927                     my $one_hold = $e->json_query({
928                         select => {
929                             au => [{
930                                 column => 'id',
931                                 transform => 'action.usr_visible_holds',
932                                 result_field => 'id'
933                             }]
934                         },
935                         from => 'au',
936                         where => {id => $e->requestor->id},
937                         limit => 1
938                     })->[0];
939
940                     if ($one_hold) {
941                         $hist_warning_needed = 1;
942                         next; # no history updates while confirmation pending
943                     }
944                 }
945             }
946
947             $settings{$key} = undef;
948
949             if ($key eq 'history.circ.retention_start') {
950                 # delete existing circulation history data.
951                 $U->simplereq(
952                     'open-ils.actor',
953                     'open-ils.actor.history.circ.clear',
954                     $self->editor->authtoken);
955             }
956         }
957     }
958
959     # Warn patrons before clearing circ/hold history
960     if ($hist_warning_needed) {
961         $self->ctx->{clear_circ_history} = $clear_circ_history;
962         $self->ctx->{clear_hold_history} = $clear_hold_history;
963         $self->ctx->{confirm_history_delete} = 1;
964     }
965
966     # Send the modified settings off to be saved
967     $U->simplereq(
968         'open-ils.actor',
969         'open-ils.actor.patron.settings.update',
970         $self->editor->authtoken, undef, \%settings);
971
972     $self->ctx->{updated_user_settings} = \%settings;
973
974     if ($use_privacy_waiver) {
975         my %waiver;
976         my $saved_entries = ();
977         my @waiver_types = qw/place_holds pickup_holds checkout_items view_history/;
978
979         # initialize our waiver hash with waiver IDs from hidden input
980         # (this ensures that we capture entries with no checked boxes)
981         foreach my $waiver_row_id ($self->cgi->param("waiver_id")) {
982             $waiver{$waiver_row_id} = {};
983         }
984
985         # process our waiver checkboxes into a hash, keyed by waiver ID
986         # (a new entry, if any, has id = 'new')
987         foreach my $waiver_type (@waiver_types) {
988             if ($self->cgi->param("waiver_$waiver_type")) {
989                 foreach my $waiver_id ($self->cgi->param("waiver_$waiver_type")) {
990                     # ensure this waiver exists in our hash
991                     $waiver{$waiver_id} = {} if !$waiver{$waiver_id};
992                     $waiver{$waiver_id}->{$waiver_type} = 1;
993                 }
994             }
995         }
996
997         foreach my $k (keys %waiver) {
998             my $w = $waiver{$k};
999             # get name from textbox
1000             $w->{name} = $self->cgi->param("waiver_name_$k");
1001             $w->{id} = $k;
1002             foreach (@waiver_types) {
1003                 $w->{$_} = 0 unless ($w->{$_});
1004             }
1005             push @$saved_entries, $w;
1006         }
1007
1008         # update patron privacy waiver entries
1009         $U->simplereq(
1010             'open-ils.actor',
1011             'open-ils.actor.patron.privacy_waiver.update',
1012             $self->editor->authtoken, undef, $saved_entries);
1013
1014         $self->ctx->{updated_waiver_entries} = $saved_entries;
1015     }
1016
1017     # re-fetch user prefs
1018     return $self->_load_user_with_prefs || Apache2::Const::OK;
1019 }
1020
1021 sub load_myopac_prefs_my_lists {
1022     my $self = shift;
1023
1024     my @user_prefs = qw/
1025         opac.lists_per_page
1026         opac.list_items_per_page
1027     /;
1028
1029     my $stat = $self->_load_user_with_prefs;
1030     return $stat if $stat;
1031
1032     return Apache2::Const::OK
1033         unless $self->cgi->request_method eq 'POST';
1034
1035     my %settings;
1036     my $set_map = $self->ctx->{user_setting_map};
1037
1038     foreach my $key (@user_prefs) {
1039         my $val = $self->cgi->param($key);
1040         $settings{$key}= $val unless $$set_map{$key} eq $val;
1041     }
1042
1043     if (keys %settings) { # we found a different setting value
1044         # Send the modified settings off to be saved
1045         $U->simplereq(
1046             'open-ils.actor',
1047             'open-ils.actor.patron.settings.update',
1048             $self->editor->authtoken, undef, \%settings);
1049
1050         # re-fetch user prefs
1051         $self->ctx->{updated_user_settings} = \%settings;
1052         $stat = $self->_load_user_with_prefs;
1053     }
1054
1055     return $stat || Apache2::Const::OK;
1056 }
1057
1058 sub fetch_user_holds {
1059     my $self = shift;
1060     my $hold_ids = shift;
1061     my $ids_only = shift;
1062     my $flesh = shift;
1063     my $available = shift;
1064     my $limit = shift;
1065     my $offset = shift;
1066
1067     my $e = $self->editor;
1068     my $all_ids; # to be used below.
1069
1070     if(!$hold_ids) {
1071         my $circ = OpenSRF::AppSession->create('open-ils.circ');
1072
1073         $hold_ids = $circ->request(
1074             'open-ils.circ.holds.id_list.retrieve.authoritative',
1075             $e->authtoken,
1076             $e->requestor->id,
1077             $available
1078         )->gather(1);
1079         $circ->kill_me;
1080
1081         $all_ids = $hold_ids;
1082         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
1083
1084     } else {
1085         $all_ids = $hold_ids;
1086     }
1087
1088     return { ids => $hold_ids, all_ids => $all_ids } if $ids_only or @$hold_ids == 0;
1089
1090     my $args = {
1091         suppress_notices => 1,
1092         suppress_transits => 1,
1093         suppress_mvr => 1,
1094         suppress_patron_details => 1
1095     };
1096
1097     # ----------------------------------------------------------------
1098     # Collect holds in batches of $batch_size for faster retrieval
1099
1100     my $batch_size = 8;
1101     my $batch_idx = 0;
1102     my $mk_req_batch = sub {
1103         my @ses;
1104         my $top_idx = $batch_idx + $batch_size;
1105         while($batch_idx < $top_idx) {
1106             my $hold_id = $hold_ids->[$batch_idx++];
1107             last unless $hold_id;
1108             my $ses = OpenSRF::AppSession->create('open-ils.circ');
1109             my $req = $ses->request(
1110                 'open-ils.circ.hold.details.retrieve',
1111                 $e->authtoken, $hold_id, $args);
1112             push(@ses, {ses => $ses, req => $req});
1113         }
1114         return @ses;
1115     };
1116
1117     my $first = 1;
1118     my(@collected, @holds, @ses);
1119
1120     while(1) {
1121         @ses = $mk_req_batch->() if $first;
1122         last if $first and not @ses;
1123
1124         if(@collected) {
1125             while(my $blob = pop(@collected)) {
1126                 my @data;
1127
1128                 # in the holds edit UI, we need to know what formats and
1129                 # languages the user selected for this hold, plus what
1130                 # formats/langs are available on the MR as a whole.
1131                 if ($blob->{hold}{hold}->hold_type eq 'M') {
1132                     my $hold = $blob->{hold}->{hold};
1133
1134                     # for MR, fetch the combined MR unapi blob
1135                     (undef, @data) = $self->get_records_and_facets(
1136                         [$hold->target], undef, {flesh => '{mra}', metarecord => 1});
1137
1138                     my $filter_org = $U->org_unit_ancestor_at_depth(
1139                         $hold->selection_ou,
1140                         $hold->selection_depth);
1141
1142                     my $filter_data = $U->simplereq(
1143                         'open-ils.circ',
1144                         'open-ils.circ.mmr.holds.filters.authoritative.atomic',
1145                         $hold->target, $filter_org, [$hold->id]
1146                     );
1147
1148                     $blob->{metarecord_filters} =
1149                         $filter_data->[0]->{metarecord};
1150                     $blob->{metarecord_selected_filters} =
1151                         $filter_data->[1]->{hold};
1152                 } else {
1153
1154                     (undef, @data) = $self->get_records_and_facets(
1155                         [$blob->{hold}->{bre_id}], undef, {flesh => '{mra}'}
1156                     );
1157                 }
1158
1159                 $blob->{marc_xml} = $data[0]->{marc_xml};
1160                 push(@holds, $blob);
1161             }
1162         }
1163
1164         for my $req_data (@ses) {
1165             push(@collected, {hold => $req_data->{req}->gather(1)});
1166             $req_data->{ses}->kill_me;
1167         }
1168
1169         @ses = $mk_req_batch->();
1170         last unless @collected or @ses;
1171         $first = 0;
1172     }
1173
1174     # put the holds back into the original server sort order
1175     my @sorted;
1176     for my $id (@$hold_ids) {
1177         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
1178     }
1179
1180     my $curbsides = [];
1181     try { # if the service is not running, just let this fail silently
1182         $curbsides = $U->simplereq(
1183             'open-ils.curbside',
1184             'open-ils.curbside.fetch_mine.atomic',
1185             $e->authtoken
1186         );
1187     } catch Error with {};
1188
1189     return { holds => \@sorted, ids => $hold_ids, all_ids => $all_ids, curbsides => $curbsides };
1190 }
1191
1192 sub load_current_curbside_libs {
1193     my $self = shift;
1194     my $ctx = $self->ctx;
1195     my $e = $self->editor;
1196     my $holds = $e->search_action_hold_request({
1197         usr              => $e->requestor->id,
1198         shelf_time       => { '!=' => undef },
1199         cancel_time      => undef,
1200         fulfillment_time => undef
1201     });
1202
1203     my %pickup_libs;
1204     for my $h (@$holds) {
1205         next if ($h->pickup_lib != $h->current_shelf_lib);
1206         $pickup_libs{$h->pickup_lib} = 1;
1207     }
1208
1209     my @curbside_pickup_libs;
1210     for my $pul (keys %pickup_libs) {
1211         push(@curbside_pickup_libs, $pul) if $ctx->{get_org_setting}->($pul, 'circ.curbside');
1212     }
1213
1214     $ctx->{curbside_pickup_libs} = [
1215         sort { $U->find_org($U->get_org_tree,$a)->name cmp $U->find_org($U->get_org_tree,$b)->name } @curbside_pickup_libs
1216     ];
1217 }
1218
1219 sub handle_hold_update {
1220     my $self = shift;
1221     my $action = shift;
1222     my $hold_ids = shift;
1223     my $e = $self->editor;
1224     my $ctx = $self->ctx;
1225     my $url;
1226
1227     my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
1228     @hold_ids = @{$self->fetch_user_holds(undef, 1)->{ids}} if $action =~ /_all/;
1229
1230     my $circ = OpenSRF::AppSession->create('open-ils.circ');
1231
1232     if($action =~ /cancel/) {
1233
1234         for my $hold_id (@hold_ids) {
1235             my $resp = $circ->request(
1236                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
1237         }
1238
1239     } elsif ($action =~ /activate|suspend/) {
1240
1241         my $vlist = [];
1242         for my $hold_id (@hold_ids) {
1243             my $vals = {id => $hold_id};
1244
1245             if($action =~ /activate/) {
1246                 $vals->{frozen} = 'f';
1247                 $vals->{thaw_date} = undef;
1248
1249             } elsif($action =~ /suspend/) {
1250                 $vals->{frozen} = 't';
1251                 # $vals->{thaw_date} = TODO;
1252             }
1253             push(@$vlist, $vals);
1254         }
1255
1256         my $resp = $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
1257         $self->ctx->{hold_suspend_post_capture} = 1 if
1258             grep {$U->event_equals($_, 'HOLD_SUSPEND_AFTER_CAPTURE')} @$resp;
1259
1260     } elsif ($action eq 'edit') {
1261
1262         my @vals = map {
1263             my $val = {"id" => $_};
1264             $val->{"frozen"} = $self->cgi->param("frozen");
1265             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
1266             $val->{"email_notify"} = $self->cgi->param("email_notify") ? 1 : 0;
1267             $val->{"phone_notify"} = $self->cgi->param("phone_notify");
1268             $val->{"sms_notify"} = ( $self->cgi->param("sms_notify") eq '' ) ? undef : $self->cgi->param("sms_notify");
1269             $val->{"sms_carrier"} = int($self->cgi->param("sms_carrier")) if $val->{"sms_notify"};
1270
1271             for my $field (qw/expire_time thaw_date/) {
1272                 # XXX TODO make this support other date formats, not just
1273                 # MM/DD/YYYY.
1274                 next unless $self->cgi->param($field) =~
1275                     m:^(\d{2})/(\d{2})/(\d{4})$:;
1276                 $val->{$field} = "$3-$1-$2";
1277             }
1278
1279             $val->{holdable_formats} = # no-op for non-MR holds
1280                 $self->compile_holdable_formats(undef, $_);
1281
1282             $val;
1283         } @hold_ids;
1284
1285         $circ->request(
1286             'open-ils.circ.hold.update.batch.atomic',
1287             $e->authtoken, undef, \@vals
1288         )->gather(1);   # LFW XXX test for failure
1289         $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds';
1290         foreach my $param (('loc', 'qtype', 'query')) {
1291             if ($self->cgi->param($param)) {
1292                 my @vals = $self->cgi->param($param);
1293                 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
1294             }
1295         }
1296     } elsif ($action eq 'curbside') { # we'll only work on one curbside slot per refresh
1297         $circ->kill_me;
1298
1299         $circ = OpenSRF::AppSession->create('open-ils.curbside');
1300
1301         # see what we're doing with curbside here...
1302         my $cs_action = $self->cgi->param("cs_action");
1303         my $slot_id = $self->cgi->param("cs_slot_id");
1304
1305         # we have an id, let's grab it if we can
1306         my $slot = $e->retrieve_action_curbside($slot_id);
1307         $slot = undef if ($slot && $slot->patron != $e->requestor->id); # nice try!
1308
1309         my $org = $self->cgi->param("cs_org");
1310         my $date = $self->cgi->param("cs_date");
1311         my $time = $self->cgi->param("cs_time");
1312         my $notes = $self->cgi->param("cs_notes");
1313
1314         if ($slot) {
1315             $org ||= $slot->org;
1316             $notes ||= $slot->notes;
1317             if ($slot->slot) {
1318                 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($slot->slot));
1319                 $date ||= $dt->strftime('%F');
1320                 $time ||= $dt->strftime('%T');
1321             }
1322         }
1323
1324         $ctx->{cs_org} = $org;
1325         $ctx->{cs_date} = $date;
1326         $ctx->{cs_time} = $time;
1327         $ctx->{cs_notes} = $notes;
1328         $ctx->{cs_slot_id} = $slot->id if ($slot);
1329         $ctx->{cs_slot} = $slot;
1330
1331         if ($cs_action eq 'reset') {
1332             $ctx->{cs_org} = $org = undef;
1333             $ctx->{cs_date} = $date = undef;
1334             $ctx->{cs_time} = $time = undef;
1335             $ctx->{cs_notes} = $notes = undef;
1336             $ctx->{cs_slot_id} = $slot_id = undef;
1337             $ctx->{cs_slot} = $slot = undef;
1338         } elsif ($cs_action eq 'save' && $org && $date && $time) {
1339             my $mode = $slot ? 'update' : 'create';
1340             $slot = $circ->request(
1341                 "open-ils.curbside.${mode}_appointment",
1342                 $e->authtoken, $e->requestor->id, $date, $time, $org, $notes
1343             )->gather(1);
1344
1345             if (defined $U->event_code($slot)) {
1346                 $self->apache->log->warn(
1347                     "error attempting to $mode a curbside appointment for patron ".
1348                     $e->requestor->id . ", got event " .  $slot->{textcode}
1349                 );
1350                 $ctx->{curbside_action_event} = $slot;
1351                 $ctx->{cs_slot} = undef;
1352             } else {
1353                 $ctx->{cs_slot} = $slot;
1354             }
1355             $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1356         } elsif ($cs_action eq 'cancel' && $slot) {
1357             my $curbsides = $U->simplereq(
1358                 'open-ils.curbside',
1359                 'open-ils.curbside.delete_appointment',
1360                 $e->authtoken, $slot->id
1361             );
1362             $url = $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/holds_curbside';
1363         } elsif ($cs_action eq 'arrive' && $slot) {
1364             my $curbsides = $U->simplereq(
1365                 'open-ils.curbside',
1366                 'open-ils.curbside.mark_arrived',
1367                 $e->authtoken, $slot->id
1368             );
1369         } elsif ($cs_action eq 'deliver' && $slot) {
1370             my $curbsides = $U->simplereq(
1371                 'open-ils.curbside',
1372                 'open-ils.curbside.mark_delivered',
1373                 $e->authtoken, $slot->id
1374             );
1375         }
1376
1377         if ($date and $org and !$ctx->{cs_times}{$org}{$date}) {
1378             $ctx->{cs_times}{$org}{$date} = $circ->request(
1379                 'open-ils.curbside.times_for_date.atomic',
1380                 $e->authtoken, $date, $org
1381             )->gather(1);
1382         }
1383     }
1384
1385     $circ->kill_me;
1386     return defined($url) ? $self->generic_redirect($url) : undef;
1387 }
1388
1389 sub load_myopac_holds {
1390     my $self = shift;
1391     my $e = $self->editor;
1392     my $ctx = $self->ctx;
1393
1394     my $limit = $self->cgi->param('limit') || 15;
1395     my $offset = $self->cgi->param('offset') || 0;
1396     my $action = $self->cgi->param('action') || '';
1397     my $hold_id = $self->cgi->param('hid');
1398     my $available = int($self->cgi->param('available') || 0);
1399
1400     my $hold_handle_result;
1401     $hold_handle_result = $self->handle_hold_update($action) if $action;
1402
1403     my $holds_object;
1404     if ($self->cgi->param('sort') ne "") {
1405         $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available);
1406     }
1407     else {
1408         $holds_object = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
1409     }
1410
1411     if($holds_object->{holds}) {
1412         $ctx->{holds} = $holds_object->{holds};
1413         $ctx->{curbside_appointments} = {};
1414
1415         $logger->info('curbside: found '.scalar(@{$holds_object->{curbsides}}).' appointments');
1416
1417         for my $cs (@{$holds_object->{curbsides}}) {
1418             if ($cs->slot) {
1419                 my $dt = DateTime::Format::ISO8601->new->parse_datetime(clean_ISO8601($cs->slot))->strftime('%F');
1420                 $ctx->{cs_times}{$cs->org}{$dt} = $U->simplereq(
1421                     'open-ils.curbside', 'open-ils.curbside.times_for_date.atomic',
1422                     $e->authtoken, $dt, $cs->org
1423                 );
1424             }
1425             $ctx->{curbside_appointments}{$cs->org} = $cs;
1426         }
1427     }
1428     $ctx->{holds_ids} = $holds_object->{all_ids};
1429     $ctx->{holds_limit} = $limit;
1430     $ctx->{holds_offset} = $offset;
1431
1432     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
1433 }
1434
1435 sub load_myopac_hold_subscriptions {
1436     my $self = shift;
1437     my $e = $self->editor;
1438     my $ctx = $self->ctx;
1439
1440     my $sub_remove = $self->cgi->param('remove');
1441
1442     if ($sub_remove and $ctx->{user}->id) {
1443         my $sub_entries = $self->editor->search_container_user_bucket_item(
1444             { bucket => $sub_remove, target_user => $ctx->{user}->id }
1445         );
1446
1447         $self->editor->xact_begin;
1448         $self->editor->delete_container_user_bucket_item($_) for @$sub_entries;
1449         $self->editor->xact_commit;
1450
1451         return $self->generic_redirect(
1452             $self->ctx->{proto} . '://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/hold_subscriptions'
1453         );
1454     }
1455
1456     return Apache2::Const::OK;
1457 }
1458
1459 my $data_filler;
1460
1461 sub load_place_hold {
1462     my $self = shift;
1463     my $ctx = $self->ctx;
1464     my $gos = $ctx->{get_org_setting};
1465     my $e = $self->editor;
1466     my $cgi = $self->cgi;
1467
1468     $self->ctx->{page} = 'place_hold';
1469     my @targets = uniq $cgi->param('hold_target');
1470     my @parts = $cgi->param('part');
1471
1472     $ctx->{hold_subscription} = $cgi->param('hold_subscription');
1473     $ctx->{hold_type} = $cgi->param('hold_type');
1474     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
1475     $ctx->{email_notify} = $cgi->param('email_notify');
1476     if ($cgi->param('phone_notify_checkbox')) {
1477         $ctx->{phone_notify} = $cgi->param('phone_notify');
1478     }
1479     if ($cgi->param('sms_notify_checkbox')) {
1480         $ctx->{sms_notify} = $cgi->param('sms_notify');
1481         $ctx->{sms_carrier} = $cgi->param('sms_carrier');
1482     }
1483
1484     return $self->generic_redirect unless @targets;
1485
1486     # Check for multiple hold placement via the num_copies widget.
1487     my $num_copies = int($cgi->param('num_copies')); # if undefined, we get 0.
1488     if ($num_copies > 1) {
1489         # Only if we have 1 hold target and no parts.
1490         if (scalar(@targets) == 1 && !$parts[0]) {
1491             # Also, only for M and T holds.
1492             if ($ctx->{hold_type} eq 'M' || $ctx->{hold_type} eq 'T') {
1493                 # Add the extra holds to @targets. NOTE: We start with
1494                 # 1 and go to < $num_copies to account for the
1495                 # existing target.
1496                 for (my $i = 1; $i < $num_copies; $i++) {
1497                     push(@targets, $targets[0]);
1498                 }
1499             }
1500         }
1501     }
1502
1503     $logger->info("Looking at hold_type: " . $ctx->{hold_type} . " and targets: @targets");
1504
1505     $ctx->{staff_recipient} = $self->editor->retrieve_actor_user([
1506         $e->requestor->id,
1507         {
1508             flesh => 1,
1509             flesh_fields => {
1510                 au => ['settings', 'card']
1511             }
1512         }
1513     ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1514     my $user_setting_map = {
1515         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) }
1516             @{
1517                 $ctx->{staff_recipient}->settings
1518             }
1519     };
1520     $ctx->{user_setting_map} = $user_setting_map;
1521
1522     my $default_notify = (defined $$user_setting_map{'opac.hold_notify'} ? $$user_setting_map{'opac.hold_notify'} : 'email:phone');
1523     if ($default_notify =~ /email/) {
1524         $ctx->{default_email_notify} = 'checked';
1525     } else {
1526         $ctx->{default_email_notify} = '';
1527     }
1528     if ($default_notify =~ /phone/) {
1529         $ctx->{default_phone_notify} = 'checked';
1530     } else {
1531         $ctx->{default_phone_notify} = '';
1532     }
1533     if ($default_notify =~ /sms/) {
1534         $ctx->{default_sms_notify} = 'checked';
1535     } else {
1536         $ctx->{default_sms_notify} = '';
1537     }
1538     if ($cgi->param('hold_suspend')) {
1539         $ctx->{frozen} = 1;
1540         # TODO: Make this support other date formats, not just mm/dd/yyyy.
1541         # We should use a date input type on the forms once it is supported by Firefox.
1542         # I didn't do that now because it is not available in a general release.
1543         if ($cgi->param('thaw_date') =~ m:^(\d{2})/(\d{2})/(\d{4})$:){
1544             eval {
1545                 my $dt = DateTime::Format::ISO8601->parse_datetime("$3-$1-$2");
1546                 $ctx->{thaw_date} = $dt->ymd;
1547             };
1548             if ($@) {
1549                 $logger->warn("ignoring invalid thaw_date when placing hold request");
1550             }
1551         }
1552     }
1553
1554
1555     # If we have a default pickup location, grab it
1556     if ($$user_setting_map{'opac.default_pickup_location'}) {
1557         $ctx->{default_pickup_lib} = $$user_setting_map{'opac.default_pickup_location'};
1558     }
1559
1560     my $request_lib = $e->requestor->ws_ou;
1561     my @hold_data;
1562     $ctx->{hold_data} = \@hold_data;
1563
1564     $data_filler = sub {
1565         my $hdata = shift;
1566         if ($ctx->{email_notify}) { $hdata->{email_notify} = $ctx->{email_notify}; }
1567         if ($ctx->{phone_notify}) { $hdata->{phone_notify} = $ctx->{phone_notify}; }
1568         if ($ctx->{sms_notify}) { $hdata->{sms_notify} = $ctx->{sms_notify}; }
1569         if ($ctx->{sms_carrier}) { $hdata->{sms_carrier} = $ctx->{sms_carrier}; }
1570         if ($ctx->{frozen}) { $hdata->{frozen} = 1; }
1571         if ($ctx->{thaw_date}) { $hdata->{thaw_date} = $ctx->{thaw_date}; }
1572         return $hdata;
1573     };
1574
1575     my $type_dispatch = {
1576         M => sub {
1577             # target metarecords
1578             my $mrecs = $e->batch_retrieve_metabib_metarecord([
1579                 \@targets,
1580                 {flesh => 1, flesh_fields => {mmr => ['master_record']}}],
1581                 {substream => 1}
1582             );
1583
1584             for my $id (@targets) {
1585                 my ($mr) = grep {$_->id eq $id} @$mrecs;
1586
1587                 my $ou_id = $cgi->param('pickup_lib') || $self->ctx->{search_ou};
1588                 my $filter_data = $U->simplereq(
1589                     'open-ils.circ',
1590                     'open-ils.circ.mmr.holds.filters.authoritative', $mr->id, $ou_id);
1591
1592                 my $holdable_formats =
1593                     $self->compile_holdable_formats($mr->id);
1594
1595                 push(@hold_data, $data_filler->({
1596                     target => $mr,
1597                     record => $mr->master_record,
1598                     holdable_formats => $holdable_formats,
1599                     metarecord_filters => $filter_data->{metarecord}
1600                 }));
1601             }
1602         },
1603         T => sub {
1604             my $recs = $e->batch_retrieve_biblio_record_entry(
1605                 [\@targets,  {flesh => 1, flesh_fields => {bre => ['metarecord']}}],
1606                 {substream => 1}
1607             );
1608
1609             for my $id (@targets) { # force back into the correct order
1610                 my ($rec) = grep {$_->id eq $id} @$recs;
1611
1612                 # NOTE: if tpac ever supports locked-down pickup libs,
1613                 # we'll need to pass a pickup_lib param along with the
1614                 # record to filter the set of monographic parts.
1615                 my $parts = $U->simplereq(
1616                     'open-ils.search',
1617                     'open-ils.search.biblio.record_hold_parts',
1618                     {record => $rec->id}
1619                 );
1620
1621                 # T holds on records that have parts are OK, but if the record has
1622                 # no non-part copies, the hold will ultimately fail.  When that
1623                 # happens, require the user to select a part.
1624                 my $part_required = 0;
1625                 if (@$parts) {
1626                     my $np_copies = $e->json_query({
1627                         select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1628                         from => {acp => {acn => {}, acpm => {type => 'left'}}},
1629                         where => {
1630                             '+acp' => {deleted => 'f'},
1631                             '+acn' => {deleted => 'f', record => $rec->id},
1632                             '+acpm' => {id => undef}
1633                         }
1634                     });
1635                     $part_required = 1 if $np_copies->[0]->{count} == 0;
1636                 }
1637
1638                 push(@hold_data, $data_filler->({
1639                     target => $rec,
1640                     record => $rec,
1641                     parts => $parts,
1642                     part_required => $part_required
1643                 }));
1644             }
1645         },
1646         V => sub {
1647             my $vols = $e->batch_retrieve_asset_call_number([
1648                 \@targets, {
1649                     "flesh" => 1,
1650                     "flesh_fields" => {"acn" => ["record"]}
1651                 }
1652             ], {substream => 1});
1653
1654             for my $id (@targets) {
1655                 my ($vol) = grep {$_->id eq $id} @$vols;
1656                 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1657             }
1658         },
1659         C => sub {
1660             my $copies = $e->batch_retrieve_asset_copy([
1661                 \@targets, {
1662                     "flesh" => 2,
1663                     "flesh_fields" => {
1664                         "acn" => ["record"],
1665                         "acp" => ["call_number"]
1666                     }
1667                 }
1668             ], {substream => 1});
1669
1670             for my $id (@targets) {
1671                 my ($copy) = grep {$_->id eq $id} @$copies;
1672                 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1673             }
1674         },
1675         I => sub {
1676             my $isses = $e->batch_retrieve_serial_issuance([
1677                 \@targets, {
1678                     "flesh" => 2,
1679                     "flesh_fields" => {
1680                         "siss" => ["subscription"], "ssub" => ["record_entry"]
1681                     }
1682                 }
1683             ], {substream => 1});
1684
1685             for my $id (@targets) {
1686                 my ($iss) = grep {$_->id eq $id} @$isses;
1687                 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1688             }
1689         }
1690         # ...
1691
1692     }->{$ctx->{hold_type}}->();
1693
1694     # caller sent bad target IDs or the wrong hold type
1695     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1696
1697     # generate the MARC xml for each record
1698     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1699
1700     my $pickup_lib = $cgi->param('pickup_lib');
1701     # no pickup lib means no holds placement, except for subscriptions
1702     return Apache2::Const::OK unless $pickup_lib || $ctx->{hold_subscription};
1703
1704     $ctx->{hold_attempt_made} = 1;
1705
1706     # Give the original CGI params back to the user in case they
1707     # want to try to override something.
1708     $ctx->{orig_params} = $cgi->Vars;
1709     delete $ctx->{orig_params}{submit};
1710     delete $ctx->{orig_params}{hold_target};
1711     delete $ctx->{orig_params}{part};
1712
1713     my $usr = $e->requestor->id;
1714
1715     if ($ctx->{is_staff}) {
1716         $logger->info("Staff initiated hold");
1717         if (!$cgi->param("hold_usr_is_requestor")) {
1718             # find the real hold target
1719
1720             $usr = $U->simplereq(
1721                 'open-ils.actor',
1722                 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1723                 $e->authtoken, $cgi->param("hold_usr"));
1724
1725             if (defined $U->event_code($usr)) {
1726                 $ctx->{hold_failed} = 1;
1727                 $ctx->{hold_failed_event} = $usr;
1728             }
1729         }
1730
1731         if ($ctx->{hold_subscription}) {
1732             # this is a batch event, hold "user" is a bucket id
1733             $logger->info("Hold Group Event requested for user bucket: " . $ctx->{hold_subscription});
1734             $usr = $e->retrieve_container_user_bucket($ctx->{hold_subscription});
1735         }
1736     }
1737
1738     # target_id is the true target_id for holds placement.
1739     # needed for attempt_hold_placement()
1740     # With the exception of P-type holds, target_id == target->id.
1741     $_->{target_id} = $_->{target}->id for @hold_data;
1742
1743     if ($ctx->{hold_type} eq 'T') {
1744
1745         # Much like quantum wave-particles, P-type holds pop into
1746         # and out of existence at the user's whim.  For our purposes,
1747         # we treat such holds as T(itle) holds with a selected_part
1748         # designation.  When the time comes to pass the hold information
1749         # off for holds possibility testing and placement, make it look
1750         # like a real P-type hold.
1751         my (@p_holds, @t_holds);
1752
1753         # Now that we have the num_copies field for mutliple title and
1754         # metarecord hold placement, the number of holds and parts
1755         # arrays can get out of sync.  We only want to parse out parts
1756         # if the numbers are equal.
1757         if ($#hold_data == $#parts) {
1758             for my $idx (0..$#parts) {
1759                 my $hdata = $hold_data[$idx];
1760                 if (my $part = $parts[$idx]) {
1761                     $hdata->{target_id} = $part;
1762                     $hdata->{selected_part} = $part;
1763                     push(@p_holds, $hdata);
1764                 } else {
1765                     push(@t_holds, $hdata);
1766                 }
1767             }
1768         } else {
1769             @t_holds = @hold_data;
1770         }
1771
1772         $self->apache->log->warn("$#parts : @t_holds");
1773
1774         $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1775         $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1776
1777     } else {
1778         $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1779     }
1780
1781     # NOTE: we are leaving the staff-placed patron barcode cookie
1782     # in place.  Otherwise, it's not possible to place more than
1783     # one hold for the patron within a staff/patron session.  This
1784     # does leave the barcode to linger longer than is ideal, but
1785     # normal staff work flow will cause the cookie to be replaced
1786     # with each new patron anyway.
1787     # TODO: See about getting the staff client to clear the cookie
1788
1789     # return to the place_hold page so the results of the hold
1790     # placement attempt can be reported to the user
1791     return Apache2::Const::OK;
1792 }
1793
1794 sub attempt_hold_placement {
1795     my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1796     my $cgi = $self->cgi;
1797     my $ctx = $self->ctx;
1798     my $e = $self->editor;
1799
1800     my $user_container = undef;
1801     if (ref($usr)) { # $usr is actually a container for a subscription...
1802         $user_container = $usr->id;
1803         return unless ($hold_type eq 'T'); # Only T-hold subscriptions for now.
1804     }
1805
1806     # First see if we should warn/block for any holds that
1807     # might have locally available items for non-subscriptions.
1808     if (!$user_container) {
1809         for my $hdata (@hold_data) {
1810             my ($local_block, $local_alert) = $self->local_avail_concern(
1811                 $hdata->{target_id}, $hold_type, $pickup_lib);
1812
1813             if ($local_block) {
1814                 $hdata->{hold_failed} = 1;
1815                 $hdata->{hold_local_block} = 1;
1816             } elsif ($local_alert) {
1817                 $hdata->{hold_failed} = 1;
1818                 $hdata->{hold_local_alert} = 1;
1819             }
1820         }
1821     }
1822
1823     my $method = $user_container
1824         ? 'open-ils.circ.holds.test_and_create.subscription_batch'
1825         : 'open-ils.circ.holds.test_and_create.batch';
1826
1827     if ($cgi->param('override')) {
1828         $method .= '.override';
1829
1830     } elsif (!$ctx->{is_staff})  {
1831
1832         $method .= '.override' if $self->ctx->{get_org_setting}->(
1833             $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1834     }
1835
1836     my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1837
1838
1839     if(@create_targets) {
1840
1841         # holdable formats may be different for each MR hold.
1842         # map each set to the ID of the target.
1843         my $holdable_formats = {};
1844         if ($hold_type eq 'M') {
1845             $holdable_formats->{$_->{target_id}} =
1846                 $_->{holdable_formats} for @hold_data;
1847         }
1848
1849         my $bses = OpenSRF::AppSession->create('open-ils.circ');
1850
1851         my @create_params = ();
1852
1853         if ($user_container) {
1854             @create_params = (
1855                 $data_filler->({
1856                     hold_type => $hold_type,
1857                     holdable_formats_map => $holdable_formats, # currently always unset, only T holds
1858                 }),
1859                 $user_container,
1860                 $create_targets[0],
1861             );
1862         } else {
1863             @create_params = (
1864                 $data_filler->({
1865                     patronid => $usr,
1866                     pickup_lib => $pickup_lib,
1867                     hold_type => $hold_type,
1868                     holdable_formats_map => $holdable_formats,
1869                 }),
1870                 \@create_targets
1871             );
1872         }
1873
1874         my $breq = $bses->request($method, $e->authtoken, @create_params);
1875
1876         while (my $resp = $breq->recv) {
1877
1878             $resp = $resp->content;
1879             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1880
1881             if ($U->event_code($resp)) {
1882                 $ctx->{general_hold_error} = $resp;
1883                 last;
1884             }
1885
1886             # subscription batch create sends an initial response to assist with client-side counting
1887             next if (
1888                 $user_container and
1889                 defined($$resp{count}) and $$resp{count} == 0
1890                 and defined($$resp{total}) and $$resp{total} > 0
1891             );
1892
1893             # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1894             my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1895             my $result = $resp->{result};
1896
1897             if ($U->event_code($result)) {
1898                 # e.g. permission denied
1899                 $hdata->{hold_failed} = 1;
1900                 $hdata->{hold_failed_event} = $result;
1901
1902             } else {
1903
1904                 if(not ref $result and $result > 0) {
1905                     # successul hold returns the hold ID
1906                     $hdata->{hold_success} = $result;
1907
1908                 } else {
1909                     # hold-specific failure event
1910                     $hdata->{hold_failed} = 1;
1911
1912                     if (ref $result eq 'HASH') {
1913                         $hdata->{hold_failed_event} = $result->{last_event};
1914
1915                         if ($result->{age_protected_copy}) {
1916                             my %temp = %{$hdata->{hold_failed_event}};
1917                             my $theTextcode = $temp{"textcode"};
1918                             $theTextcode.=".override";
1919                             $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1920                             $hdata->{age_protect} = 1;
1921                         } else {
1922                             $hdata->{could_override} = $result->{place_unfillable} ||
1923                                 $self->test_could_override($hdata->{hold_failed_event});
1924                         }
1925                     } elsif (ref $result eq 'ARRAY') {
1926                         $hdata->{hold_failed_event} = $result->[0];
1927
1928                         if ($result->[3]) { # age_protect_only
1929                             my %temp = %{$hdata->{hold_failed_event}};
1930                             my $theTextcode = $temp{"textcode"};
1931                             $theTextcode.=".override";
1932                             $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1933                             $hdata->{age_protect} = 1;
1934                         } else {
1935                             $hdata->{could_override} = $result->[4] || # place_unfillable
1936                                 $self->test_could_override($hdata->{hold_failed_event});
1937                         }
1938                     }
1939                 }
1940             }
1941         }
1942
1943         $bses->kill_me;
1944     }
1945
1946     if ($self->cgi->param('clear_cart')) {
1947         $self->clear_anon_cache;
1948     }
1949 }
1950
1951 # pull the selected formats and languages for metarecord holds
1952 # from the CGI params and map them into the JSON holdable
1953 # formats...er, format.
1954 # if no metarecord is provided, we'll pull it from the target
1955 # of the provided hold.
1956 sub compile_holdable_formats {
1957     my ($self, $mr_id, $hold_id) = @_;
1958     my $e = $self->editor;
1959     my $cgi = $self->cgi;
1960
1961     # exit early if not needed
1962     return undef unless
1963         grep /metarecord_formats_|metarecord_langs_/,
1964         $cgi->param;
1965
1966     # CGI params are based on the MR id, since during hold placement
1967     # we have no old ID.  During hold edit, map the hold ID back to
1968     # the metarecod target.
1969     $mr_id =
1970         $e->retrieve_action_hold_request($hold_id)->target
1971         unless $mr_id;
1972
1973     my $format_attr = $self->ctx->{get_cgf}->(
1974         'opac.metarecord.holds.format_attr');
1975
1976     if (!$format_attr) {
1977         $logger->error("Missing config.global_flag: ".
1978             "opac.metarecord.holds.format_attr!");
1979         return "";
1980     }
1981
1982     $format_attr = $format_attr->value;
1983
1984     # during hold placement or edit submission, the user selects
1985     # which of the available formats/langs are acceptable.
1986     # Capture those here as the holdable_formats for the MR hold.
1987     my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1988     my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1989
1990     # map the selected attrs into the JSON holdable_formats structure
1991     my $blob = {};
1992     if (@selected_formats) {
1993         $blob->{0} = [
1994             map { {_attr => $format_attr, _val => $_} }
1995             @selected_formats
1996         ];
1997     }
1998     if (@selected_langs) {
1999         $blob->{1} = [
2000             map { {_attr => 'item_lang', _val => $_} }
2001             @selected_langs
2002         ];
2003     }
2004
2005     return OpenSRF::Utils::JSON->perl2JSON($blob);
2006 }
2007
2008 sub fetch_user_circs {
2009     my $self = shift;
2010     my $flesh = shift; # flesh bib data, etc.
2011     my $circ_ids = shift;
2012     my $limit = shift;
2013     my $offset = shift;
2014
2015     my $e = $self->editor;
2016
2017     my @circ_ids;
2018
2019     if($circ_ids) {
2020         @circ_ids = @$circ_ids;
2021
2022     } else {
2023
2024         my $query = {
2025             select => {circ => ['id']},
2026             from => 'circ',
2027             where => {
2028                 '+circ' => {
2029                     usr => $e->requestor->id,
2030                     checkin_time => undef,
2031                     '-or' => [
2032                         {stop_fines => undef},
2033                         {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
2034                     ],
2035                 }
2036             },
2037             order_by => {circ => ['due_date']}
2038         };
2039
2040         $query->{limit} = $limit if $limit;
2041         $query->{offset} = $offset if $offset;
2042
2043         my $ids = $e->json_query($query);
2044         @circ_ids = map {$_->{id}} @$ids;
2045     }
2046
2047     return [] unless @circ_ids;
2048
2049     my $qflesh = {
2050         flesh => 3,
2051         flesh_fields => {
2052             circ => ['target_copy'],
2053             acp => ['call_number','parts'],
2054             acn => ['record','owning_lib','prefix','suffix']
2055         }
2056     };
2057
2058     $e->xact_begin;
2059     my $circs = $e->search_action_circulation(
2060         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
2061
2062     my @circs;
2063     for my $circ (@$circs) {
2064         push(@circs, {
2065             circ => $circ,
2066             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
2067                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
2068                 undef  # pre-cat copy, use the dummy title/author instead
2069         });
2070     }
2071     $e->rollback;
2072
2073     # make sure the final list is in the correct order
2074     my @sorted_circs;
2075     for my $id (@circ_ids) {
2076         push(
2077             @sorted_circs,
2078             (grep { $_->{circ}->id == $id } @circs)
2079         );
2080     }
2081
2082     return \@sorted_circs;
2083 }
2084
2085
2086 sub handle_circ_renew {
2087     my $self = shift;
2088     my $action = shift;
2089     my $ctx = $self->ctx;
2090
2091     my @renew_ids = $self->cgi->param('circ');
2092
2093     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2094
2095     # TODO: fire off renewal calls in batches to speed things up
2096     my @responses;
2097     for my $circ (@$circs) {
2098
2099         my $evt = $U->simplereq(
2100             'open-ils.circ',
2101             'open-ils.circ.renew',
2102             $self->editor->authtoken,
2103             {
2104                 patron_id => $self->editor->requestor->id,
2105                 copy_id => $circ->{circ}->target_copy,
2106                 opac_renewal => 1
2107             }
2108         );
2109
2110         # TODO return these, then insert them into the circ data
2111         # blob that is shoved into the template for each circ
2112         # so the template won't have to match them
2113         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2114     }
2115
2116     return @responses;
2117 }
2118
2119 sub load_myopac_circs {
2120     my $self = shift;
2121     my $e = $self->editor;
2122     my $ctx = $self->ctx;
2123
2124     $ctx->{circs} = [];
2125     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2126     my $offset = $self->cgi->param('offset') || 0;
2127     my $action = $self->cgi->param('action') || '';
2128
2129     # perform the renewal first if necessary
2130     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2131
2132     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2133
2134     my $success_renewals = 0;
2135     my $failed_renewals = 0;
2136     for my $data (@{$ctx->{circs}}) {
2137         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2138
2139         if($resp) {
2140             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2141
2142             # extract the fail_part, if present, from the event payload;
2143             # since # the payload is an acp object in some cases,
2144             # blindly looking for a # 'fail_part' key in the template can
2145             # break things
2146             $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2147                 $evt->{payload}->{fail_part} :
2148                 '';
2149
2150             $data->{renewal_response} = $evt;
2151             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2152             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2153         }
2154     }
2155
2156     $ctx->{success_renewals} = $success_renewals;
2157     $ctx->{failed_renewals} = $failed_renewals;
2158
2159     return Apache2::Const::OK;
2160 }
2161
2162 sub load_myopac_circ_history {
2163     my $self = shift;
2164     my $e = $self->editor;
2165     my $ctx = $self->ctx;
2166     my $limit = $self->cgi->param('limit') || 15;
2167     my $offset = $self->cgi->param('offset') || 0;
2168     my $action = $self->cgi->param('action') || '';
2169
2170     my $circ_handle_result;
2171     $circ_handle_result = $self->handle_circ_update($action) if $action;
2172
2173     $ctx->{circ_history_limit} = $limit;
2174     $ctx->{circ_history_offset} = $offset;
2175
2176     # Defer limitation to circ_history.tt2 when sorting
2177     if ($self->cgi->param('sort')) {
2178         $limit = undef;
2179         $offset = undef;
2180     }
2181
2182     $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2183     return Apache2::Const::OK;
2184 }
2185
2186 # if 'flesh' is set, copy data etc. is loaded and the return value is
2187 # a hash of 'circ' and 'marc_xml'.  Othwerwise, it's just a list of
2188 # auch objects.
2189 sub fetch_user_circ_history {
2190     my ($self, $flesh, $limit, $offset) = @_;
2191     my $e = $self->editor;
2192
2193     my %limits = ();
2194     $limits{offset} = $offset if defined $offset;
2195     $limits{limit} = $limit if defined $limit;
2196
2197     my %flesh_ops = (
2198         flesh => 3,
2199         flesh_fields => {
2200             auch => ['target_copy','source_circ'],
2201             acp => ['call_number','parts'],
2202             acn => ['record','prefix','suffix']
2203         },
2204     );
2205
2206     $e->xact_begin;
2207     my $circs = $e->search_action_user_circ_history(
2208         [
2209             {usr => $e->requestor->id},
2210             {   # order newest to oldest by default
2211                 order_by => {auch => 'xact_start DESC'},
2212                 $flesh ? %flesh_ops : (),
2213                 %limits
2214             }
2215         ],
2216         {substream => 1}
2217     );
2218     $e->rollback;
2219
2220     return $circs unless $flesh;
2221
2222     $e->xact_begin;
2223     my @circs;
2224     my %unapi_cache = ();
2225     for my $circ (@$circs) {
2226         if ($circ->target_copy->call_number->id == -1) {
2227             push(@circs, {
2228                 circ => $circ,
2229                 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2230             });
2231             next;
2232         }
2233         my $bre_id = $circ->target_copy->call_number->record->id;
2234         my $unapi;
2235         if (exists $unapi_cache{$bre_id}) {
2236             $unapi = $unapi_cache{$bre_id};
2237         } else {
2238             my $result = $e->json_query({
2239                 from => [
2240                     'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2241                 ]
2242             });
2243             if ($result) {
2244                 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2245             }
2246         }
2247         if ($unapi) {
2248             push(@circs, {
2249                 circ => $circ,
2250                 marc_xml => $unapi
2251             });
2252         } else {
2253             push(@circs, {
2254                 circ => $circ,
2255                 marc_xml => undef # failed, but try to go on
2256             });
2257         }
2258     }
2259     $e->rollback;
2260
2261     return \@circs;
2262 }
2263
2264 sub handle_circ_update {
2265     my $self     = shift;
2266     my $action   = shift;
2267     my $circ_ids = shift;
2268
2269     $circ_ids //= [$self->cgi->param('circ_id')];
2270
2271     if ($action =~ /delete/) {
2272         my $options = {
2273             circ_ids => $circ_ids,
2274         };
2275
2276         $U->simplereq(
2277             'open-ils.actor',
2278             'open-ils.actor.history.circ.clear',
2279             $self->editor->authtoken,
2280             $options
2281         );
2282     }
2283
2284     return;
2285 }
2286
2287 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
2288 sub load_myopac_hold_history {
2289     my $self = shift;
2290     my $e = $self->editor;
2291     my $ctx = $self->ctx;
2292     my $limit = $self->cgi->param('limit') || 15;
2293     my $offset = $self->cgi->param('offset') || 0;
2294     $ctx->{hold_history_limit} = $limit;
2295     $ctx->{hold_history_offset} = $offset;
2296
2297     my $hold_ids = $e->json_query({
2298         select => {
2299             au => [{
2300                 column => 'id',
2301                 transform => 'action.usr_visible_holds',
2302                 result_field => 'id'
2303             }]
2304         },
2305         from => 'au',
2306         where => {id => $e->requestor->id}
2307     });
2308
2309     my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2310     if($holds_object->{holds}) {
2311         $ctx->{holds} = $holds_object->{holds};
2312     }
2313     $ctx->{hold_history_ids} = $holds_object->{all_ids};
2314
2315     return Apache2::Const::OK;
2316 }
2317
2318 sub load_myopac_payment_form {
2319     my $self = shift;
2320     my $r;
2321     my $e = $self->editor;
2322
2323     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2324
2325     if ( ! $self->cgi->param('last_chance') # only do this once
2326         && $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.enabled')
2327         && $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'Stripe') {
2328         my $skey = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.secretkey');
2329         my $currency = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.currency');
2330         my $stripe = Business::Stripe->new(-api_key => $skey);
2331         my $intent = $stripe->api('post', 'payment_intents',
2332             amount                => $self->ctx->{fines}->{balance_owed} * 100,
2333             currency              => $currency || 'usd'
2334         );
2335         if ($stripe->success) {
2336             $self->ctx->{stripe_client_secret} = $stripe->success()->{client_secret};
2337         } else {
2338             $logger->error('Error initializing Stripe: ' . Dumper($stripe->error));
2339             $self->ctx->{cc_configuration_error} = 1;
2340         }
2341     }
2342
2343     if ($r) { return $r; }
2344     $r = $self->prepare_extended_user_info and return $r;
2345
2346     return Apache2::Const::OK;
2347 }
2348
2349 # TODO: add other filter options as params/configs/etc.
2350 sub load_myopac_payments {
2351     my $self = shift;
2352     my $limit = $self->cgi->param('limit') || 20;
2353     my $offset = $self->cgi->param('offset') || 0;
2354     my $e = $self->editor;
2355
2356     $self->ctx->{payment_history_limit} = $limit;
2357     $self->ctx->{payment_history_offset} = $offset;
2358
2359     my $args = {};
2360     $args->{limit} = $limit if $limit;
2361     $args->{offset} = $offset if $offset;
2362
2363     if (my $max_age = $self->ctx->{get_org_setting}->(
2364         $e->requestor->home_ou, "opac.payment_history_age_limit"
2365     )) {
2366         my $min_ts = DateTime->now(
2367             "time_zone" => DateTime::TimeZone->new("name" => "local"),
2368         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2369
2370         $logger->info("XXX min_ts: $min_ts");
2371         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2372     }
2373
2374     $self->ctx->{payments} = $U->simplereq(
2375         'open-ils.actor',
2376         'open-ils.actor.user.payments.retrieve.atomic',
2377         $e->authtoken, $e->requestor->id, $args);
2378
2379     return Apache2::Const::OK;
2380 }
2381
2382 # 1. caches the form parameters
2383 # 2. loads the credit card payment "Processing..." page
2384 sub load_myopac_pay_init {
2385     my $self = shift;
2386     my $cache = OpenSRF::Utils::Cache->new('global');
2387
2388     my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2389
2390     if (!@payment_xacts) {
2391         # for consistency with load_myopac_payment_form() and
2392         # to preserve backwards compatibility, if no xacts are
2393         # selected, assume all (applicable) transactions are wanted.
2394         my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2395         return $stat if $stat;
2396         @payment_xacts =
2397             map { $_->{xact}->id } (
2398                 @{$self->ctx->{fines}->{circulation}},
2399                 @{$self->ctx->{fines}->{grocery}}
2400         );
2401     }
2402
2403     return $self->generic_redirect unless @payment_xacts;
2404
2405     my $cc_args = {"where_process" => 1};
2406
2407     $cc_args->{$_} = $self->cgi->param($_) for (qw/
2408         number cvv2 expire_year expire_month billing_first
2409         billing_last billing_address billing_city billing_state
2410         billing_zip stripe_payment_intent stripe_client_secret
2411     /);
2412
2413     my $cache_args = {
2414         cc_args => $cc_args,
2415         user => $self->ctx->{user}->id,
2416         xacts => \@payment_xacts
2417     };
2418
2419     # generate a temporary cache token and cache the form data
2420     my $token = md5_hex($$ . time() . rand());
2421     $cache->put_cache($token, $cache_args, 30);
2422
2423     $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2424
2425     # after we render the processing page, we quickly redirect to submit
2426     # the actual payment.  The refresh url contains the payment token.
2427     # It also contains the list of xact IDs, which allows us to clear the
2428     # cache at the earliest possible time while leaving a trace of which
2429     # transactions we were processing, so the UI can bring the user back
2430     # to the payment form w/ the same xacts if the payment fails.
2431
2432     my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2433     $refresh .= ";xact=$_" for @payment_xacts;
2434     $self->ctx->{refresh} = $refresh;
2435
2436     return Apache2::Const::OK;
2437 }
2438
2439 # retrieve the cached CC payment info and send off for processing
2440 sub load_myopac_pay {
2441     my $self = shift;
2442     my $token = $self->ctx->{page_args}->[0];
2443     return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2444
2445     my $cache = OpenSRF::Utils::Cache->new('global');
2446     my $cache_args = $cache->get_cache($token);
2447     $cache->delete_cache($token);
2448
2449     # this page is loaded immediately after the token is created.
2450     # if the cached data is not there, it's because of an invalid
2451     # token (or cache failure) and not because of a timeout.
2452     return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2453
2454     my @payment_xacts = @{$cache_args->{xacts}};
2455     my $cc_args = $cache_args->{cc_args};
2456
2457     # as an added security check, verify the user submitting
2458     # the form is the same as the user whose data was cached
2459     return Apache2::Const::HTTP_BAD_REQUEST unless
2460         $cache_args->{user} == $self->ctx->{user}->id;
2461
2462     $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2463
2464     my $r;
2465     $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2466
2467     # balance_owed is computed specifically from the fines we're paying
2468     if ($self->ctx->{fines}->{balance_owed} <= 0) {
2469         $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2470         return Apache2::Const::HTTP_BAD_REQUEST;
2471     }
2472
2473     my $args = {
2474         "cc_args" => $cc_args,
2475         "userid" => $self->ctx->{user}->id,
2476         "payment_type" => "credit_card_payment",
2477         "payments" => $self->prepare_fines_for_payment  # should be safe after self->prepare_fines
2478     };
2479
2480     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2481         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2482     );
2483
2484     $self->ctx->{"payment_response"} = $resp;
2485
2486     unless ($resp->{"textcode"}) {
2487         $self->ctx->{printable_receipt} = $U->simplereq(
2488         "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2489         $self->editor->authtoken, $resp->{payments}
2490         );
2491     }
2492
2493     return Apache2::Const::OK;
2494 }
2495
2496 sub load_myopac_receipt_print {
2497     my $self = shift;
2498
2499     $self->ctx->{printable_receipt} = $U->simplereq(
2500     "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2501     $self->editor->authtoken, [$self->cgi->param("payment")]
2502     );
2503
2504     return Apache2::Const::OK;
2505 }
2506
2507 sub load_myopac_receipt_email {
2508     my $self = shift;
2509
2510     # The following ML method doesn't actually check whether the user in
2511     # question has an email address, so we do.
2512     if ($self->ctx->{user}->email) {
2513         $self->ctx->{email_receipt_result} = $U->simplereq(
2514         "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2515         $self->editor->authtoken, [$self->cgi->param("payment")]
2516         );
2517     } else {
2518         $self->ctx->{email_receipt_result} =
2519             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2520     }
2521
2522     return Apache2::Const::OK;
2523 }
2524
2525 sub prepare_fines {
2526     my ($self, $limit, $offset, $id_list) = @_;
2527
2528     # XXX TODO: check for failure after various network calls
2529
2530     # It may be unclear, but this result structure lumps circulation and
2531     # reservation fines together, and keeps grocery fines separate.
2532     $self->ctx->{"fines"} = {
2533         "circulation" => [],
2534         "grocery" => [],
2535         "total_paid" => 0,
2536         "total_owed" => 0,
2537         "balance_owed" => 0
2538     };
2539
2540     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2541
2542     # TODO: This should really be a ML call, but the existing calls
2543     # return an excessive amount of data and don't offer streaming
2544
2545     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2546
2547     my $req = $cstore->request(
2548         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2549         {
2550             usr => $self->editor->requestor->id,
2551             balance_owed => {'!=' => 0},
2552             ($id_list && @$id_list ? ("id" => $id_list) : ()),
2553         },
2554         {
2555             flesh => 4,
2556             flesh_fields => {
2557                 mobts => [qw/grocery circulation reservation/],
2558                 bresv => ['target_resource_type'],
2559                 brt => ['record'],
2560                 mg => ['billings'],
2561                 mb => ['btype'],
2562                 circ => ['target_copy'],
2563                 acp => ['call_number'],
2564                 acn => ['record']
2565             },
2566             order_by => { mobts => 'xact_start' },
2567             %paging
2568         }
2569     );
2570
2571     # Collect $$ amounts from each transaction for summing below.
2572     my (@paid_amounts, @owed_amounts, @balance_amounts);
2573
2574     while(my $resp = $req->recv) {
2575         my $mobts = $resp->content;
2576         my $circ = $mobts->circulation;
2577
2578         my $last_billing;
2579         if($mobts->grocery) {
2580             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2581             $last_billing = pop(@billings);
2582         }
2583
2584         push(@paid_amounts, $mobts->total_paid);
2585         push(@owed_amounts, $mobts->total_owed);
2586         push(@balance_amounts, $mobts->balance_owed);
2587
2588         my $marc_xml = undef;
2589         if ($mobts->xact_type eq 'reservation' and
2590             $mobts->reservation->target_resource_type->record) {
2591             $marc_xml = XML::LibXML->new->parse_string(
2592                 $mobts->reservation->target_resource_type->record->marc
2593             );
2594         } elsif ($mobts->xact_type eq 'circulation' and
2595             $circ->target_copy->call_number->id != -1) {
2596             $marc_xml = XML::LibXML->new->parse_string(
2597                 $circ->target_copy->call_number->record->marc
2598             );
2599         }
2600
2601         push(
2602             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2603             {
2604                 xact => $mobts,
2605                 last_grocery_billing => $last_billing,
2606                 marc_xml => $marc_xml
2607             }
2608         );
2609     }
2610
2611     $cstore->kill_me;
2612
2613     $self->ctx->{"fines"}->{total_paid}   = $U->fpsum(@paid_amounts);
2614     $self->ctx->{"fines"}->{total_owed}   = $U->fpsum(@owed_amounts);
2615     $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2616
2617     return;
2618 }
2619
2620 sub prepare_fines_for_payment {
2621     # This assumes $self->prepare_fines has already been run
2622     my ($self) = @_;
2623
2624     my @results = ();
2625     if ($self->ctx->{fines}) {
2626         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2627             @{$self->ctx->{fines}->{circulation}},
2628             @{$self->ctx->{fines}->{grocery}}
2629         );
2630     }
2631
2632     return \@results;
2633 }
2634
2635 sub load_myopac_main {
2636     my $self = shift;
2637     my $limit = $self->cgi->param('limit') || 0;
2638     my $offset = $self->cgi->param('offset') || 0;
2639     $self->ctx->{search_ou} = $self->_get_search_lib();
2640     $self->ctx->{user}->notes(
2641         $self->editor->search_actor_usr_message({
2642             usr => $self->ctx->{user}->id,
2643             pub => 't'
2644         })
2645     );
2646     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2647 }
2648
2649 sub load_myopac_update_email {
2650     my $self = shift;
2651     my $e = $self->editor;
2652     my $ctx = $self->ctx;
2653     my $email = $self->cgi->param('email') || '';
2654     my $current_pw = $self->cgi->param('current_pw') || '';
2655
2656     # needed for most up-to-date email address
2657     if (my $r = $self->prepare_extended_user_info) { return $r };
2658
2659     return Apache2::Const::OK
2660         unless $self->cgi->request_method eq 'POST';
2661
2662     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2663         $ctx->{invalid_email} = $email;
2664         return Apache2::Const::OK;
2665     }
2666
2667     my $stat = $U->simplereq(
2668         'open-ils.actor',
2669         'open-ils.actor.user.email.update',
2670         $e->authtoken, $email, $current_pw);
2671
2672     if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2673         $ctx->{password_incorrect} = 1;
2674         return Apache2::Const::OK;
2675     }
2676
2677     unless ($self->cgi->param("redirect_to")) {
2678         my $url = $self->apache->unparsed_uri;
2679         $url =~ s/update_email/prefs/;
2680
2681         return $self->generic_redirect($url);
2682     }
2683
2684     return $self->generic_redirect;
2685 }
2686
2687 sub load_myopac_update_username {
2688     my $self = shift;
2689     my $e = $self->editor;
2690     my $ctx = $self->ctx;
2691     my $username = $self->cgi->param('username') || '';
2692     my $current_pw = $self->cgi->param('current_pw') || '';
2693
2694     $self->prepare_extended_user_info;
2695
2696     my $allow_change = 1;
2697     my $regex_check;
2698     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2699     if(defined($lock_usernames) and $lock_usernames == 1) {
2700         # Policy says no username changes
2701         $allow_change = 0;
2702     } else {
2703         # We want this further down.
2704         $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2705         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2706         if(!$username_unlimit) {
2707             if(!$regex_check) {
2708                 # Default is "starts with a number"
2709                 $regex_check = '^\d+';
2710             }
2711             # You already have a username?
2712             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2713                 $allow_change = 0;
2714             }
2715         }
2716     }
2717     if(!$allow_change) {
2718         my $url = $self->apache->unparsed_uri;
2719         $url =~ s/update_username/prefs/;
2720
2721         return $self->generic_redirect($url);
2722     }
2723
2724     return Apache2::Const::OK
2725         unless $self->cgi->request_method eq 'POST';
2726
2727     unless($username and $username !~ /\s/) { # any other username restrictions?
2728         $ctx->{invalid_username} = $username;
2729         return Apache2::Const::OK;
2730     }
2731
2732     # New username can't look like a barcode if we have a barcode regex
2733     if($regex_check and $username =~ /$regex_check/) {
2734         $ctx->{invalid_username} = $username;
2735         return Apache2::Const::OK;
2736     }
2737
2738     # New username has to look like a username if we have a username regex
2739     $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2740     if($regex_check and $username !~ /$regex_check/) {
2741         $ctx->{invalid_username} = $username;
2742         return Apache2::Const::OK;
2743     }
2744
2745     if($username ne $e->requestor->usrname) {
2746
2747         my $evt = $U->simplereq(
2748             'open-ils.actor',
2749             'open-ils.actor.user.username.update',
2750             $e->authtoken, $username, $current_pw);
2751
2752         if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2753             $ctx->{password_incorrect} = 1;
2754             return Apache2::Const::OK;
2755         }
2756
2757         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2758             $ctx->{username_exists} = $username;
2759             return Apache2::Const::OK;
2760         }
2761     }
2762
2763     my $url = $self->apache->unparsed_uri;
2764     $url =~ s/update_username/prefs/;
2765
2766     return $self->generic_redirect($url);
2767 }
2768
2769 sub load_myopac_update_password {
2770     my $self = shift;
2771     my $e = $self->editor;
2772     my $ctx = $self->ctx;
2773
2774     return Apache2::Const::OK
2775         unless $self->cgi->request_method eq 'POST';
2776
2777     my $current_pw = $self->cgi->param('current_pw') || '';
2778     my $new_pw = $self->cgi->param('new_pw') || '';
2779     my $new_pw2 = $self->cgi->param('new_pw2') || '';
2780
2781     unless($new_pw eq $new_pw2) {
2782         $ctx->{password_nomatch} = 1;
2783         return Apache2::Const::OK;
2784     }
2785
2786     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2787
2788     if(!$pw_regex) {
2789         # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2790         $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2791     }
2792
2793     if($pw_regex and $new_pw !~ /$pw_regex/) {
2794         $ctx->{password_invalid} = 1;
2795         return Apache2::Const::OK;
2796     }
2797
2798     my $evt = $U->simplereq(
2799         'open-ils.actor',
2800         'open-ils.actor.user.password.update',
2801         $e->authtoken, $new_pw, $current_pw);
2802
2803
2804     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2805         $ctx->{password_incorrect} = 1;
2806         return Apache2::Const::OK;
2807     }
2808
2809     my $url = $self->apache->unparsed_uri;
2810     $url =~ s/update_password/prefs/;
2811
2812     return $self->generic_redirect($url);
2813 }
2814
2815 sub _update_bookbag_metadata {
2816     my ($self, $bookbag) = @_;
2817
2818     $bookbag->name($self->cgi->param("name"));
2819     $bookbag->description($self->cgi->param("description"));
2820
2821     return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2822     return 0;
2823 }
2824
2825 sub _get_lists_per_page {
2826     my $self = shift;
2827
2828     if($self->editor->requestor) {
2829         $self->timelog("Checking for opac.lists_per_page preference");
2830         # See if the user has a lists per page preference
2831         my $ipp = $self->editor->search_actor_user_setting({
2832             usr => $self->editor->requestor->id,
2833             name => 'opac.lists_per_page'
2834         })->[0];
2835         $self->timelog("Got opac.lists_per_page preference");
2836         return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2837     }
2838     return 10; # default
2839 }
2840
2841 sub _get_items_per_page {
2842     my $self = shift;
2843
2844     if($self->editor->requestor) {
2845         $self->timelog("Checking for opac.list_items_per_page preference");
2846         # See if the user has a list items per page preference
2847         my $ipp = $self->editor->search_actor_user_setting({
2848             usr => $self->editor->requestor->id,
2849             name => 'opac.list_items_per_page'
2850         })->[0];
2851         $self->timelog("Got opac.list_items_per_page preference");
2852         return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2853     }
2854     return 10; # default
2855 }
2856
2857 sub load_myopac_bookbags {
2858     my $self = shift;
2859     my $e = $self->editor;
2860     my $ctx = $self->ctx;
2861     my $limit = $self->_get_lists_per_page || 10;
2862     my $offset = $self->cgi->param('offset') || 0;
2863
2864     $ctx->{bookbags_limit} = $limit;
2865     $ctx->{bookbags_offset} = $offset;
2866
2867     # for list item pagination
2868     my $item_limit = $self->_get_items_per_page;
2869     my $item_page = $self->cgi->param('item_page') || 1;
2870     my $item_offset = ($item_page - 1) * $item_limit;
2871     $ctx->{bookbags_item_page} = $item_page;
2872
2873     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
2874     $e->xact_begin; # replication...
2875
2876     my $rv = $self->load_mylist;
2877     unless($rv eq Apache2::Const::OK) {
2878         $e->rollback;
2879         return $rv;
2880     }
2881
2882     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
2883         [
2884             {owner => $e->requestor->id, btype => 'bookbag'}, {
2885                 order_by => {cbreb => 'name'},
2886                 limit => $limit,
2887                 offset => $offset
2888             }
2889         ],
2890         {substream => 1}
2891     );
2892
2893     if(!$ctx->{bookbags}) {
2894         $e->rollback;
2895         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2896     }
2897
2898     # We load the user prefs to get their default bookbag.
2899     $self->_load_user_with_prefs;
2900
2901     # We also want a total count of the user's bookbags.
2902     my $q = {
2903         'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
2904         'from' => 'cbreb',
2905         'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
2906     };
2907     my $r = $e->json_query($q);
2908     $ctx->{bookbag_count} = $r->[0]->{'count'};
2909
2910     # If the user wants a specific bookbag's items, load them.
2911
2912     if ($self->cgi->param("bbid")) {
2913         my ($bookbag) =
2914             grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
2915
2916         if ($bookbag) {
2917             my $query = $self->_prepare_bookbag_container_query(
2918                 $bookbag->id, $sorter, $modifier
2919             );
2920
2921             # Calculate total count of the items in selected bookbag.
2922             # This total includes record entries that have no assets available.
2923             my $bb_search_results = $U->simplereq(
2924                 "open-ils.search", "open-ils.search.biblio.multiclass.query",
2925                 {"limit" => 1, "offset" => 0}, $query
2926             ); # we only need the count, so do the actual search with limit=1
2927
2928             if ($bb_search_results) {
2929                 $ctx->{bb_item_count} = $bb_search_results->{count};
2930             } else {
2931                 $logger->warn("search failed in load_myopac_bookbags()");
2932                 $ctx->{bb_item_count} = 0; # fallback value
2933             }
2934
2935             #calculate page count
2936             $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
2937
2938             if ( ($self->cgi->param("action") || '') eq "editmeta") {
2939                 if (!$self->_update_bookbag_metadata($bookbag))  {
2940                     $e->rollback;
2941                     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2942                 } else {
2943                     $e->commit;
2944                     my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
2945                         $bookbag->id;
2946
2947                     foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
2948                         if ($self->cgi->param($param)) {
2949                             my @vals = $self->cgi->param($param);
2950                             $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
2951                         }
2952                     }
2953
2954                     return $self->generic_redirect($url);
2955                 }
2956             }
2957
2958             # we're done with our CStoreEditor.  Rollback here so
2959             # later calls don't cause a timeout, resulting in a
2960             # transaction rollback under the covers.
2961             $e->rollback;
2962
2963
2964             # For list items pagination
2965             my $args = {
2966                 "limit" => $item_limit,
2967                 "offset" => $item_offset
2968             };
2969
2970             my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
2971                 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
2972
2973             # capture pref_ou for callnumber filter/display
2974             $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
2975
2976             # search for local callnumbers for display
2977             my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
2978
2979             my (undef, @recs) = $self->get_records_and_facets(
2980                 [ map {$_->target_biblio_record_entry->id} @$items ],
2981                 undef,
2982                 {
2983                     flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
2984                     flesh_depth => 1,
2985                     site => $ctx->{get_aou}->($focus_ou)->shortname,
2986                     pref_lib => $ctx->{pref_ou}
2987                 }
2988             );
2989
2990             $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
2991
2992             $bookbag->items($items);
2993         }
2994     }
2995
2996     # If we have add_rec, we got here from the "Add to new list"
2997     # or "See all" popmenu items.
2998     if (my $add_rec = $self->cgi->param('add_rec')) {
2999         $self->ctx->{add_rec} = $add_rec;
3000         # But not in the staff client, 'cause that breaks things.
3001         unless ($self->ctx->{is_staff}) {
3002             # allow caller to provide the where_from in cases where
3003             # the referer is an intermediate error page
3004             if ($self->cgi->param('where_from')) {
3005                 $self->ctx->{where_from} = $self->cgi->param('where_from');
3006             } else {
3007                 $self->ctx->{where_from} = $self->ctx->{referer};
3008                 if ( my $anchor = $self->cgi->param('anchor') ) {
3009                     $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
3010                 }
3011             }
3012         }
3013     }
3014
3015     # this rollback may be a dupe, but that's OK because
3016     # cstoreditor ignores dupe rollbacks
3017     $e->rollback;
3018
3019     return Apache2::Const::OK;
3020 }
3021
3022
3023 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
3024 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
3025 sub load_myopac_bookbag_update {
3026     my ($self, $action, $list_id, @hold_recs) = @_;
3027     my $e = $self->editor;
3028     my $cgi = $self->cgi;
3029
3030     # save_notes is effectively another action, but is passed in a separate
3031     # CGI parameter for what are really just layout reasons.
3032     $action = 'save_notes' if $cgi->param('save_notes');
3033     $action ||= $cgi->param('action');
3034
3035     $list_id ||= $cgi->param('list') || $cgi->param('bbid');
3036
3037     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
3038     my @selected_item = $cgi->param('selected_item');
3039     my $shared = $cgi->param('shared');
3040     my $move_cart = $cgi->param('move_cart');
3041     my $name = $cgi->param('name');
3042     my $description = $cgi->param('description');
3043     my $success = 0;
3044     my $list;
3045
3046     # bail out if user is attempting an action that requires
3047     # that at least one list item be selected
3048     if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
3049         ($action eq 'place_hold' || $action eq 'print' ||
3050          $action eq 'email' || $action eq 'del_item')) {
3051         my $url = $self->ctx->{referer};
3052         $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
3053         return $self->generic_redirect($url);
3054     }
3055
3056     # This url intentionally leaves off the edit_notes parameter, but
3057     # may need to add some back in for paging.
3058
3059     my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
3060         $self->ctx->{opac_root} . "/myopac/lists?";
3061
3062     foreach my $param (('loc', 'qtype', 'query', 'sort')) {
3063         if ($cgi->param($param)) {
3064             my @vals = $cgi->param($param);
3065             $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3066         }
3067     }
3068
3069     if ($action eq 'create') {
3070
3071         if ($name) {
3072             $list = Fieldmapper::container::biblio_record_entry_bucket->new;
3073             $list->name($name);
3074             $list->description($description);
3075             $list->owner($e->requestor->id);
3076             $list->btype('bookbag');
3077             $list->pub($shared ? 't' : 'f');
3078             $success = $U->simplereq('open-ils.actor',
3079                 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
3080             if (ref($success) ne 'HASH') {
3081                 $list_id = (ref($success)) ? $success->id : $success;
3082                 if (scalar @add_rec) {
3083                     foreach my $add_rec (@add_rec) {
3084                         my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3085                         $item->bucket($list_id);
3086                         $item->target_biblio_record_entry($add_rec);
3087                         $success = $U->simplereq('open-ils.actor',
3088                                                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3089                         last unless $success;
3090                     }
3091                 }
3092                 if ($move_cart) {
3093                     my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3094                     foreach my $add_rec (@$list) {
3095                         my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3096                         $item->bucket($list_id);
3097                         $item->target_biblio_record_entry($add_rec);
3098                         $success = $U->simplereq('open-ils.actor',
3099                                                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3100                         last unless $success;
3101                     }
3102                     $self->clear_anon_cache;
3103                 }
3104             }
3105             $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3106
3107         } else { # no name
3108             $self->ctx->{bucket_failure_noname} = 1;
3109         }
3110
3111     } elsif($action eq 'place_hold') {
3112
3113         # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3114         my $from_basket = scalar(@hold_recs);
3115         unless (@hold_recs) {
3116             if (@selected_item) {
3117                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3118                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3119             }
3120         }
3121
3122         return Apache2::Const::OK unless @hold_recs;
3123         $logger->info("placing holds from list page on: @hold_recs");
3124
3125         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3126         $url .= ';hold_target=' . $_ for @hold_recs;
3127         $url .= ';from_basket=1' if $from_basket;
3128         foreach my $param (('loc', 'qtype', 'query')) {
3129             if ($cgi->param($param)) {
3130                 my @vals = $cgi->param($param);
3131                 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3132             }
3133         }
3134         return $self->generic_redirect($url);
3135
3136     } elsif ($action eq 'print') {
3137         my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3138         $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3139         if (!$incoming_sort) {
3140             ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3141         }
3142         if (!$incoming_sort) {
3143             $incoming_sort = 'author';
3144         }
3145
3146         $incoming_sort =~ s/sort.*$//;
3147
3148         $self->ctx->{sort} = $incoming_sort;
3149         $self->ctx->{sort_dir} = $sort_dir;
3150
3151         my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3152         my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3153         my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3154         return $self->load_mylist_print($temp_cache_key);
3155     } elsif ($action eq 'email') {
3156         my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3157         $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3158         if (!$incoming_sort) {
3159             ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3160         }
3161         if (!$incoming_sort) {
3162             $incoming_sort = 'author';
3163         }
3164
3165         $incoming_sort =~ s/sort.*$//;
3166
3167         $self->ctx->{sort} = $incoming_sort;
3168         $self->ctx->{sort_dir} = $sort_dir;
3169
3170         my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3171         my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3172         my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3173         return $self->load_mylist_email($temp_cache_key);
3174     } else {
3175
3176         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3177
3178         return Apache2::Const::HTTP_BAD_REQUEST unless
3179             $list and $list->owner == $e->requestor->id;
3180     }
3181
3182     if($action eq 'delete') {
3183         $success = $U->simplereq('open-ils.actor',
3184             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3185         if ($success) {
3186             # We check to see if we're deleting the user's default list.
3187             $self->_load_user_with_prefs;
3188             my $settings_map = $self->ctx->{user_setting_map};
3189             if ($$settings_map{'opac.default_list'} == $list_id) {
3190                 # We unset the user's opac.default_list setting.
3191                 $success = $U->simplereq(
3192                     'open-ils.actor',
3193                     'open-ils.actor.patron.settings.update',
3194                     $e->authtoken,
3195                     $e->requestor->id,
3196                     { 'opac.default_list' => 0 }
3197                 );
3198             }
3199         }
3200     } elsif($action eq 'show') {
3201         unless($U->is_true($list->pub)) {
3202             $list->pub('t');
3203             $success = $U->simplereq('open-ils.actor',
3204                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3205         }
3206
3207     } elsif($action eq 'hide') {
3208         if($U->is_true($list->pub)) {
3209             $list->pub('f');
3210             $success = $U->simplereq('open-ils.actor',
3211                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3212         }
3213
3214     } elsif($action eq 'rename') {
3215         if($name) {
3216             $list->name($name);
3217             $success = $U->simplereq('open-ils.actor',
3218                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3219         }
3220
3221     } elsif($action eq 'add_rec') {
3222         foreach my $add_rec (@add_rec) {
3223             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3224             $item->bucket($list_id);
3225             $item->target_biblio_record_entry($add_rec);
3226             $success = $U->simplereq('open-ils.actor',
3227                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3228             last unless $success;
3229         }
3230         # Redirect back where we came from if we have an anchor parameter:
3231         if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3232             $url = $self->ctx->{referer};
3233             $url =~ s/#.*|$/#$anchor/;
3234         } elsif ($cgi->param('where_from')) {
3235             # Or, if we have a "where_from" parameter.
3236             $url = $cgi->param('where_from');
3237         }
3238     } elsif ($action eq 'del_item') {
3239         foreach (@selected_item) {
3240             $success = $U->simplereq(
3241                 'open-ils.actor',
3242                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3243             );
3244             last unless $success;
3245         }
3246     } elsif ($action eq 'save_notes') {
3247         $success = $self->update_bookbag_item_notes;
3248         $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3249     } elsif ($action eq 'make_default') {
3250         $success = $U->simplereq(
3251             'open-ils.actor',
3252             'open-ils.actor.patron.settings.update',
3253             $e->authtoken,
3254             $list->owner,
3255             { 'opac.default_list' => $list_id }
3256         );
3257     } elsif ($action eq 'remove_default') {
3258         $success = $U->simplereq(
3259             'open-ils.actor',
3260             'open-ils.actor.patron.settings.update',
3261             $e->authtoken,
3262             $list->owner,
3263             { 'opac.default_list' => 0 }
3264         );
3265     }
3266
3267     return $self->generic_redirect($url) if $success;
3268
3269     $self->ctx->{where_from} = $cgi->param('where_from');
3270     $self->ctx->{bucket_action} = $action;
3271     $self->ctx->{bucket_action_failed} = 1;
3272     return Apache2::Const::OK;
3273 }
3274
3275 sub update_bookbag_item_notes {
3276     my ($self) = @_;
3277     my $e = $self->editor;
3278
3279     my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3280     my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3281
3282     # We're going to leverage an API call that's already been written to check
3283     # permissions appropriately.
3284
3285     my $a = create OpenSRF::AppSession("open-ils.actor");
3286     my $method = "open-ils.actor.container.item_note.cud";
3287
3288     for my $note_key (@note_keys) {
3289         my $note;
3290
3291         my $id = ($note_key =~ /(\d+)/)[0];
3292
3293         if (!($note =
3294             $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3295             my $event = $e->die_event;
3296             $self->apache->log->warn(
3297                 "error retrieving cbrebin id $id, got event " .
3298                 $event->{textcode}
3299             );
3300             $a->kill_me;
3301             $self->ctx->{bucket_action_event} = $event;
3302             return;
3303         }
3304
3305         if (length($self->cgi->param($note_key))) {
3306             $note->ischanged(1);
3307             $note->note($self->cgi->param($note_key));
3308         } else {
3309             $note->isdeleted(1);
3310         }
3311
3312         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3313
3314         if (defined $U->event_code($r)) {
3315             $self->apache->log->warn(
3316                 "attempt to modify cbrebin " . $note->id .
3317                 " returned event " .  $r->{textcode}
3318             );
3319             $e->rollback;
3320             $a->kill_me;
3321             $self->ctx->{bucket_action_event} = $r;
3322             return;
3323         }
3324     }
3325
3326     for my $item_key (@item_keys) {
3327         my $id = int(($item_key =~ /(\d+)/)[0]);
3328         my $text = $self->cgi->param($item_key);
3329
3330         chomp $text;
3331         next unless length $text;
3332
3333         my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3334         $note->isnew(1);
3335         $note->item($id);
3336         $note->note($text);
3337
3338         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3339
3340         if (defined $U->event_code($r)) {
3341             $self->apache->log->warn(
3342                 "attempt to create cbrebin for item " . $note->item .
3343                 " returned event " .  $r->{textcode}
3344             );
3345             $e->rollback;
3346             $a->kill_me;
3347             $self->ctx->{bucket_action_event} = $r;
3348             return;
3349         }
3350     }
3351
3352     $a->kill_me;
3353     return 1;   # success
3354 }
3355
3356 sub load_myopac_bookbag_print {
3357     my ($self) = @_;
3358
3359     my $id = int($self->cgi->param("list"));
3360
3361     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3362
3363     my $item_search =
3364         $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3365
3366     my $bbag;
3367
3368     # Get the bookbag object itself, assuming we're allowed to.
3369     if ($self->editor->allowed("VIEW_CONTAINER")) {
3370
3371         $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3372     } else {
3373         my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3374             {
3375                 "id" => $id,
3376                 "-or" => {
3377                     "owner" => $self->editor->requestor->id,
3378                     "pub" => "t"
3379                 }
3380             }
3381         ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3382
3383         $bbag = pop @$bookbags;
3384     }
3385
3386     # If we have a bookbag we're allowed to look at, issue the A/T event
3387     # to get CSV, passing as a user param that search query we built before.
3388     if ($bbag) {
3389         $self->ctx->{csv} = $U->fire_object_event(
3390             undef, "container.biblio_record_entry_bucket.csv",
3391             $bbag, $self->editor->requestor->home_ou,
3392             undef, {"item_search" => $item_search}
3393         );
3394     }
3395
3396     # Create a reasonable filename and set the content disposition to
3397     # provoke browser download dialogs.
3398     (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3399
3400     return $self->set_file_download_headers("$filename.csv");
3401 }
3402
3403 sub load_myopac_circ_history_export {
3404     my $self = shift;
3405     my $e = $self->editor;
3406     my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3407
3408     my $circs = $self->fetch_user_circ_history(1);
3409
3410     $self->ctx->{csv}->{circs} = $circs;
3411     return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3412
3413 }
3414
3415 sub load_myopac_reservations {
3416     my $self = shift;
3417     my $e = $self->editor;
3418     my $ctx = $self->ctx;
3419
3420     my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3421         $e->authtoken, undef
3422     );
3423
3424     $ctx->{reservations} = $upcoming;
3425     return Apache2::Const::OK;
3426
3427 }
3428
3429 sub load_password_reset {
3430     my $self = shift;
3431     my $cgi = $self->cgi;
3432     my $ctx = $self->ctx;
3433     my $barcode = $cgi->param('barcode');
3434     my $username = $cgi->param('username');
3435     my $email = $cgi->param('email');
3436     my $pwd1 = $cgi->param('pwd1');
3437     my $pwd2 = $cgi->param('pwd2');
3438     my $uuid = $ctx->{page_args}->[0];
3439
3440     if ($uuid) {
3441
3442         $logger->info("patron password reset with uuid $uuid");
3443
3444         if ($pwd1 and $pwd2) {
3445
3446             if ($pwd1 eq $pwd2) {
3447
3448                 my $response = $U->simplereq(
3449                     'open-ils.actor',
3450                     'open-ils.actor.patron.password_reset.commit',
3451                     $uuid, $pwd1);
3452
3453                 $logger->info("patron password reset response " . Dumper($response));
3454
3455                 if ($U->event_code($response)) { # non-success event
3456
3457                     my $code = $response->{textcode};
3458
3459                     if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3460                         $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3461                     }
3462
3463                     if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3464                         $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3465                     }
3466
3467                 } else { # success
3468
3469                     $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3470                 }
3471
3472             } else { # passwords not equal
3473
3474                 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3475             }
3476
3477         } else { # 2 password values needed
3478
3479             $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3480         }
3481
3482     } elsif ($barcode or $username) {
3483
3484         my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3485         push(@params, $email) if $email;
3486
3487         $U->simplereq(
3488             'open-ils.actor',
3489             'open-ils.actor.patron.password_reset.request', @params);
3490
3491         $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3492     }
3493
3494     $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3495     return Apache2::Const::OK;
3496 }
3497
3498 1;