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