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