]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
LP1993305 Comprise SmartPay support, UI bits
[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 OK, but if the record has
1626                 # no non-part copies, the hold will ultimately fail.  When that
1627                 # happens, require the user to select a part.
1628                 my $part_required = 0;
1629                 if (@$parts) {
1630                     my $np_copies = $e->json_query({
1631                         select => { acp => [{column => 'id', transform => 'count', alias => 'count'}]},
1632                         from => {acp => {acn => {}, acpm => {type => 'left'}}},
1633                         where => {
1634                             '+acp' => {deleted => 'f'},
1635                             '+acn' => {deleted => 'f', record => $rec->id},
1636                             '+acpm' => {id => undef}
1637                         }
1638                     });
1639                     $part_required = 1 if $np_copies->[0]->{count} == 0;
1640                 }
1641
1642                 push(@hold_data, $data_filler->({
1643                     target => $rec,
1644                     record => $rec,
1645                     parts => $parts,
1646                     part_required => $part_required
1647                 }));
1648             }
1649         },
1650         V => sub {
1651             my $vols = $e->batch_retrieve_asset_call_number([
1652                 \@targets, {
1653                     "flesh" => 1,
1654                     "flesh_fields" => {"acn" => ["record"]}
1655                 }
1656             ], {substream => 1});
1657
1658             for my $id (@targets) {
1659                 my ($vol) = grep {$_->id eq $id} @$vols;
1660                 push(@hold_data, $data_filler->({target => $vol, record => $vol->record}));
1661             }
1662         },
1663         C => sub {
1664             my $copies = $e->batch_retrieve_asset_copy([
1665                 \@targets, {
1666                     "flesh" => 2,
1667                     "flesh_fields" => {
1668                         "acn" => ["record"],
1669                         "acp" => ["call_number"]
1670                     }
1671                 }
1672             ], {substream => 1});
1673
1674             for my $id (@targets) {
1675                 my ($copy) = grep {$_->id eq $id} @$copies;
1676                 push(@hold_data, $data_filler->({target => $copy, record => $copy->call_number->record}));
1677             }
1678         },
1679         I => sub {
1680             my $isses = $e->batch_retrieve_serial_issuance([
1681                 \@targets, {
1682                     "flesh" => 2,
1683                     "flesh_fields" => {
1684                         "siss" => ["subscription"], "ssub" => ["record_entry"]
1685                     }
1686                 }
1687             ], {substream => 1});
1688
1689             for my $id (@targets) {
1690                 my ($iss) = grep {$_->id eq $id} @$isses;
1691                 push(@hold_data, $data_filler->({target => $iss, record => $iss->subscription->record_entry}));
1692             }
1693         }
1694         # ...
1695
1696     }->{$ctx->{hold_type}}->();
1697
1698     # caller sent bad target IDs or the wrong hold type
1699     return Apache2::Const::HTTP_BAD_REQUEST unless @hold_data;
1700
1701     # generate the MARC xml for each record
1702     $_->{marc_xml} = XML::LibXML->new->parse_string($_->{record}->marc) for @hold_data;
1703
1704     my $pickup_lib = $cgi->param('pickup_lib');
1705     # no pickup lib means no holds placement, except for subscriptions
1706     return Apache2::Const::OK unless $pickup_lib || $ctx->{hold_subscription};
1707
1708     $ctx->{hold_attempt_made} = 1;
1709
1710     # Give the original CGI params back to the user in case they
1711     # want to try to override something.
1712     $ctx->{orig_params} = $cgi->Vars;
1713     delete $ctx->{orig_params}{submit};
1714     delete $ctx->{orig_params}{hold_target};
1715     delete $ctx->{orig_params}{part};
1716
1717     my $usr = $e->requestor->id;
1718
1719     if ($ctx->{is_staff}) {
1720         $logger->info("Staff initiated hold");
1721         if (!$cgi->param("hold_usr_is_requestor")) {
1722             # find the real hold target
1723
1724             $usr = $U->simplereq(
1725                 'open-ils.actor',
1726                 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
1727                 $e->authtoken, $cgi->param("hold_usr"));
1728
1729             if (defined $U->event_code($usr)) {
1730                 $ctx->{hold_failed} = 1;
1731                 $ctx->{hold_failed_event} = $usr;
1732             }
1733         }
1734
1735         if ($ctx->{hold_subscription}) {
1736             # this is a batch event, hold "user" is a bucket id
1737             $logger->info("Hold Group Event requested for user bucket: " . $ctx->{hold_subscription});
1738             $usr = $e->retrieve_container_user_bucket($ctx->{hold_subscription});
1739         }
1740     }
1741
1742     # target_id is the true target_id for holds placement.
1743     # needed for attempt_hold_placement()
1744     # With the exception of P-type holds, target_id == target->id.
1745     $_->{target_id} = $_->{target}->id for @hold_data;
1746
1747     if ($ctx->{hold_type} eq 'T') {
1748
1749         # Much like quantum wave-particles, P-type holds pop into
1750         # and out of existence at the user's whim.  For our purposes,
1751         # we treat such holds as T(itle) holds with a selected_part
1752         # designation.  When the time comes to pass the hold information
1753         # off for holds possibility testing and placement, make it look
1754         # like a real P-type hold.
1755         my (@p_holds, @t_holds);
1756
1757         # Now that we have the num_copies field for mutliple title and
1758         # metarecord hold placement, the number of holds and parts
1759         # arrays can get out of sync.  We only want to parse out parts
1760         # if the numbers are equal.
1761         if ($#hold_data == $#parts) {
1762             for my $idx (0..$#parts) {
1763                 my $hdata = $hold_data[$idx];
1764                 if (my $part = $parts[$idx]) {
1765                     $hdata->{target_id} = $part;
1766                     $hdata->{selected_part} = $part;
1767                     push(@p_holds, $hdata);
1768                 } else {
1769                     push(@t_holds, $hdata);
1770                 }
1771             }
1772         } else {
1773             @t_holds = @hold_data;
1774         }
1775
1776         $self->apache->log->warn("$#parts : @t_holds");
1777
1778         $self->attempt_hold_placement($usr, $pickup_lib, 'P', @p_holds) if @p_holds;
1779         $self->attempt_hold_placement($usr, $pickup_lib, 'T', @t_holds) if @t_holds;
1780
1781     } else {
1782         $self->attempt_hold_placement($usr, $pickup_lib, $ctx->{hold_type}, @hold_data);
1783     }
1784
1785     # NOTE: we are leaving the staff-placed patron barcode cookie
1786     # in place.  Otherwise, it's not possible to place more than
1787     # one hold for the patron within a staff/patron session.  This
1788     # does leave the barcode to linger longer than is ideal, but
1789     # normal staff work flow will cause the cookie to be replaced
1790     # with each new patron anyway.
1791     # TODO: See about getting the staff client to clear the cookie
1792
1793     # return to the place_hold page so the results of the hold
1794     # placement attempt can be reported to the user
1795     return Apache2::Const::OK;
1796 }
1797
1798 sub attempt_hold_placement {
1799     my ($self, $usr, $pickup_lib, $hold_type, @hold_data) = @_;
1800     my $cgi = $self->cgi;
1801     my $ctx = $self->ctx;
1802     my $e = $self->editor;
1803
1804     my $user_container = undef;
1805     if (ref($usr)) { # $usr is actually a container for a subscription...
1806         $user_container = $usr->id;
1807         return unless ($hold_type eq 'T'); # Only T-hold subscriptions for now.
1808     }
1809
1810     # First see if we should warn/block for any holds that
1811     # might have locally available items for non-subscriptions.
1812     if (!$user_container) {
1813         for my $hdata (@hold_data) {
1814             my ($local_block, $local_alert) = $self->local_avail_concern(
1815                 $hdata->{target_id}, $hold_type, $pickup_lib);
1816
1817             if ($local_block) {
1818                 $hdata->{hold_failed} = 1;
1819                 $hdata->{hold_local_block} = 1;
1820             } elsif ($local_alert) {
1821                 $hdata->{hold_failed} = 1;
1822                 $hdata->{hold_local_alert} = 1;
1823             }
1824         }
1825     }
1826
1827     my $method = $user_container
1828         ? 'open-ils.circ.holds.test_and_create.subscription_batch'
1829         : 'open-ils.circ.holds.test_and_create.batch';
1830
1831     if ($cgi->param('override')) {
1832         $method .= '.override';
1833
1834     } elsif (!$ctx->{is_staff})  {
1835
1836         $method .= '.override' if $self->ctx->{get_org_setting}->(
1837             $e->requestor->home_ou, "opac.patron.auto_overide_hold_events");
1838     }
1839
1840     my @create_targets = map {$_->{target_id}} (grep { !$_->{hold_failed} } @hold_data);
1841
1842
1843     if(@create_targets) {
1844
1845         # holdable formats may be different for each MR hold.
1846         # map each set to the ID of the target.
1847         my $holdable_formats = {};
1848         if ($hold_type eq 'M') {
1849             $holdable_formats->{$_->{target_id}} =
1850                 $_->{holdable_formats} for @hold_data;
1851         }
1852
1853         my $bses = OpenSRF::AppSession->create('open-ils.circ');
1854
1855         my @create_params = ();
1856
1857         if ($user_container) {
1858             @create_params = (
1859                 $data_filler->({
1860                     hold_type => $hold_type,
1861                     holdable_formats_map => $holdable_formats, # currently always unset, only T holds
1862                 }),
1863                 $user_container,
1864                 $create_targets[0],
1865             );
1866         } else {
1867             @create_params = (
1868                 $data_filler->({
1869                     patronid => $usr,
1870                     pickup_lib => $pickup_lib,
1871                     hold_type => $hold_type,
1872                     holdable_formats_map => $holdable_formats,
1873                 }),
1874                 \@create_targets
1875             );
1876         }
1877
1878         my $breq = $bses->request($method, $e->authtoken, @create_params);
1879
1880         while (my $resp = $breq->recv) {
1881
1882             $resp = $resp->content;
1883             $logger->info('batch hold placement result: ' . OpenSRF::Utils::JSON->perl2JSON($resp));
1884
1885             if ($U->event_code($resp)) {
1886                 $ctx->{general_hold_error} = $resp;
1887                 last;
1888             }
1889
1890             # subscription batch create sends an initial response to assist with client-side counting
1891             next if (
1892                 $user_container and
1893                 defined($$resp{count}) and $$resp{count} == 0
1894                 and defined($$resp{total}) and $$resp{total} > 0
1895             );
1896
1897             # Skip those that had the hold_success or hold_failed fields set for duplicate holds placement.
1898             my ($hdata) = grep {$_->{target_id} eq $resp->{target} && !($_->{hold_failed} || $_->{hold_success})} @hold_data;
1899             my $result = $resp->{result};
1900
1901             if ($U->event_code($result)) {
1902                 # e.g. permission denied
1903                 $hdata->{hold_failed} = 1;
1904                 $hdata->{hold_failed_event} = $result;
1905
1906             } else {
1907
1908                 if(not ref $result and $result > 0) {
1909                     # successul hold returns the hold ID
1910                     $hdata->{hold_success} = $result;
1911
1912                 } else {
1913                     # hold-specific failure event
1914                     $hdata->{hold_failed} = 1;
1915
1916                     if (ref $result eq 'HASH') {
1917                         $hdata->{hold_failed_event} = $result->{last_event};
1918
1919                         if ($result->{age_protected_copy}) {
1920                             my %temp = %{$hdata->{hold_failed_event}};
1921                             my $theTextcode = $temp{"textcode"};
1922                             $theTextcode.=".override";
1923                             $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1924                             $hdata->{age_protect} = 1;
1925                         } else {
1926                             $hdata->{could_override} = $result->{place_unfillable} ||
1927                                 $self->test_could_override($hdata->{hold_failed_event});
1928                         }
1929                     } elsif (ref $result eq 'ARRAY') {
1930                         $hdata->{hold_failed_event} = $result->[0];
1931
1932                         if ($result->[3]) { # age_protect_only
1933                             my %temp = %{$hdata->{hold_failed_event}};
1934                             my $theTextcode = $temp{"textcode"};
1935                             $theTextcode.=".override";
1936                             $hdata->{could_override} = $self->editor->allowed( $theTextcode );
1937                             $hdata->{age_protect} = 1;
1938                         } else {
1939                             $hdata->{could_override} = $result->[4] || # place_unfillable
1940                                 $self->test_could_override($hdata->{hold_failed_event});
1941                         }
1942                     }
1943                 }
1944             }
1945         }
1946
1947         $bses->kill_me;
1948     }
1949
1950     if ($self->cgi->param('clear_cart')) {
1951         $self->clear_anon_cache;
1952     }
1953 }
1954
1955 # pull the selected formats and languages for metarecord holds
1956 # from the CGI params and map them into the JSON holdable
1957 # formats...er, format.
1958 # if no metarecord is provided, we'll pull it from the target
1959 # of the provided hold.
1960 sub compile_holdable_formats {
1961     my ($self, $mr_id, $hold_id) = @_;
1962     my $e = $self->editor;
1963     my $cgi = $self->cgi;
1964
1965     # exit early if not needed
1966     return undef unless
1967         grep /metarecord_formats_|metarecord_langs_/,
1968         $cgi->param;
1969
1970     # CGI params are based on the MR id, since during hold placement
1971     # we have no old ID.  During hold edit, map the hold ID back to
1972     # the metarecod target.
1973     $mr_id =
1974         $e->retrieve_action_hold_request($hold_id)->target
1975         unless $mr_id;
1976
1977     my $format_attr = $self->ctx->{get_cgf}->(
1978         'opac.metarecord.holds.format_attr');
1979
1980     if (!$format_attr) {
1981         $logger->error("Missing config.global_flag: ".
1982             "opac.metarecord.holds.format_attr!");
1983         return "";
1984     }
1985
1986     $format_attr = $format_attr->value;
1987
1988     # during hold placement or edit submission, the user selects
1989     # which of the available formats/langs are acceptable.
1990     # Capture those here as the holdable_formats for the MR hold.
1991     my @selected_formats = $cgi->param("metarecord_formats_$mr_id");
1992     my @selected_langs = $cgi->param("metarecord_langs_$mr_id");
1993
1994     # map the selected attrs into the JSON holdable_formats structure
1995     my $blob = {};
1996     if (@selected_formats) {
1997         $blob->{0} = [
1998             map { {_attr => $format_attr, _val => $_} }
1999             @selected_formats
2000         ];
2001     }
2002     if (@selected_langs) {
2003         $blob->{1} = [
2004             map { {_attr => 'item_lang', _val => $_} }
2005             @selected_langs
2006         ];
2007     }
2008
2009     return OpenSRF::Utils::JSON->perl2JSON($blob);
2010 }
2011
2012 sub fetch_user_circs {
2013     my $self = shift;
2014     my $flesh = shift; # flesh bib data, etc.
2015     my $circ_ids = shift;
2016     my $limit = shift;
2017     my $offset = shift;
2018
2019     my $e = $self->editor;
2020
2021     my @circ_ids;
2022
2023     if($circ_ids) {
2024         @circ_ids = @$circ_ids;
2025
2026     } else {
2027
2028         my $query = {
2029             select => {circ => ['id']},
2030             from => 'circ',
2031             where => {
2032                 '+circ' => {
2033                     usr => $e->requestor->id,
2034                     checkin_time => undef,
2035                     '-or' => [
2036                         {stop_fines => undef},
2037                         {stop_fines => {'not in' => ['LOST','CLAIMSRETURNED','LONGOVERDUE']}}
2038                     ],
2039                 }
2040             },
2041             order_by => {circ => ['due_date']}
2042         };
2043
2044         $query->{limit} = $limit if $limit;
2045         $query->{offset} = $offset if $offset;
2046
2047         my $ids = $e->json_query($query);
2048         @circ_ids = map {$_->{id}} @$ids;
2049     }
2050
2051     return [] unless @circ_ids;
2052
2053     my $qflesh = {
2054         flesh => 3,
2055         flesh_fields => {
2056             circ => ['target_copy'],
2057             acp => ['call_number','parts'],
2058             acn => ['record','owning_lib','prefix','suffix']
2059         }
2060     };
2061
2062     $e->xact_begin;
2063     my $circs = $e->search_action_circulation(
2064         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
2065
2066     my @circs;
2067     for my $circ (@$circs) {
2068         push(@circs, {
2069             circ => $circ,
2070             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
2071                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
2072                 undef  # pre-cat copy, use the dummy title/author instead
2073         });
2074     }
2075     $e->rollback;
2076
2077     # make sure the final list is in the correct order
2078     my @sorted_circs;
2079     for my $id (@circ_ids) {
2080         push(
2081             @sorted_circs,
2082             (grep { $_->{circ}->id == $id } @circs)
2083         );
2084     }
2085
2086     return \@sorted_circs;
2087 }
2088
2089
2090 sub handle_circ_renew {
2091     my $self = shift;
2092     my $action = shift;
2093     my $ctx = $self->ctx;
2094
2095     my @renew_ids = $self->cgi->param('circ');
2096
2097     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
2098
2099     # TODO: fire off renewal calls in batches to speed things up
2100     my @responses;
2101     for my $circ (@$circs) {
2102
2103         my $evt = $U->simplereq(
2104             'open-ils.circ',
2105             'open-ils.circ.renew',
2106             $self->editor->authtoken,
2107             {
2108                 patron_id => $self->editor->requestor->id,
2109                 copy_id => $circ->{circ}->target_copy,
2110                 opac_renewal => 1
2111             }
2112         );
2113
2114         # TODO return these, then insert them into the circ data
2115         # blob that is shoved into the template for each circ
2116         # so the template won't have to match them
2117         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
2118     }
2119
2120     return @responses;
2121 }
2122
2123 sub load_myopac_circs {
2124     my $self = shift;
2125     my $e = $self->editor;
2126     my $ctx = $self->ctx;
2127
2128     $ctx->{circs} = [];
2129     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
2130     my $offset = $self->cgi->param('offset') || 0;
2131     my $action = $self->cgi->param('action') || '';
2132
2133     # perform the renewal first if necessary
2134     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
2135
2136     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
2137
2138     my $success_renewals = 0;
2139     my $failed_renewals = 0;
2140     for my $data (@{$ctx->{circs}}) {
2141         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
2142
2143         if($resp) {
2144             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
2145
2146             # extract the fail_part, if present, from the event payload;
2147             # since # the payload is an acp object in some cases,
2148             # blindly looking for a # 'fail_part' key in the template can
2149             # break things
2150             $evt->{fail_part} = (ref($evt->{payload}) eq 'HASH' && exists $evt->{payload}->{fail_part}) ?
2151                 $evt->{payload}->{fail_part} :
2152                 '';
2153
2154             $data->{renewal_response} = $evt;
2155             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
2156             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
2157         }
2158     }
2159
2160     $ctx->{success_renewals} = $success_renewals;
2161     $ctx->{failed_renewals} = $failed_renewals;
2162
2163     return Apache2::Const::OK;
2164 }
2165
2166 sub load_myopac_circ_history {
2167     my $self = shift;
2168     my $e = $self->editor;
2169     my $ctx = $self->ctx;
2170     my $limit = $self->cgi->param('limit') || 15;
2171     my $offset = $self->cgi->param('offset') || 0;
2172     my $action = $self->cgi->param('action') || '';
2173
2174     my $circ_handle_result;
2175     $circ_handle_result = $self->handle_circ_update($action) if $action;
2176
2177     $ctx->{circ_history_limit} = $limit;
2178     $ctx->{circ_history_offset} = $offset;
2179
2180     # Defer limitation to circ_history.tt2 when sorting
2181     if ($self->cgi->param('sort')) {
2182         $limit = undef;
2183         $offset = undef;
2184     }
2185
2186     $ctx->{circs} = $self->fetch_user_circ_history(1, $limit, $offset);
2187     return Apache2::Const::OK;
2188 }
2189
2190 # if 'flesh' is set, copy data etc. is loaded and the return value is
2191 # a hash of 'circ' and 'marc_xml'.  Othwerwise, it's just a list of
2192 # auch objects.
2193 sub fetch_user_circ_history {
2194     my ($self, $flesh, $limit, $offset) = @_;
2195     my $e = $self->editor;
2196
2197     my %limits = ();
2198     $limits{offset} = $offset if defined $offset;
2199     $limits{limit} = $limit if defined $limit;
2200
2201     my %flesh_ops = (
2202         flesh => 3,
2203         flesh_fields => {
2204             auch => ['target_copy','source_circ'],
2205             acp => ['call_number','parts'],
2206             acn => ['record','prefix','suffix']
2207         },
2208     );
2209
2210     $e->xact_begin;
2211     my $circs = $e->search_action_user_circ_history(
2212         [
2213             {usr => $e->requestor->id},
2214             {   # order newest to oldest by default
2215                 order_by => {auch => 'xact_start DESC'},
2216                 $flesh ? %flesh_ops : (),
2217                 %limits
2218             }
2219         ],
2220         {substream => 1}
2221     );
2222     $e->rollback;
2223
2224     return $circs unless $flesh;
2225
2226     $e->xact_begin;
2227     my @circs;
2228     my %unapi_cache = ();
2229     for my $circ (@$circs) {
2230         if ($circ->target_copy->call_number->id == -1) {
2231             push(@circs, {
2232                 circ => $circ,
2233                 marc_xml => undef # pre-cat copy, use the dummy title/author instead
2234             });
2235             next;
2236         }
2237         my $bre_id = $circ->target_copy->call_number->record->id;
2238         my $unapi;
2239         if (exists $unapi_cache{$bre_id}) {
2240             $unapi = $unapi_cache{$bre_id};
2241         } else {
2242             my $result = $e->json_query({
2243                 from => [
2244                     'unapi.bre', $bre_id, 'marcxml','record','{mra}', undef, undef, undef
2245                 ]
2246             });
2247             if ($result) {
2248                 $unapi_cache{$bre_id} = $unapi = XML::LibXML->new->parse_string($result->[0]->{'unapi.bre'});
2249             }
2250         }
2251         if ($unapi) {
2252             push(@circs, {
2253                 circ => $circ,
2254                 marc_xml => $unapi
2255             });
2256         } else {
2257             push(@circs, {
2258                 circ => $circ,
2259                 marc_xml => undef # failed, but try to go on
2260             });
2261         }
2262     }
2263     $e->rollback;
2264
2265     return \@circs;
2266 }
2267
2268 sub handle_circ_update {
2269     my $self     = shift;
2270     my $action   = shift;
2271     my $circ_ids = shift;
2272
2273     $circ_ids //= [$self->cgi->param('circ_id')];
2274
2275     if ($action =~ /delete/) {
2276         my $options = {
2277             circ_ids => $circ_ids,
2278         };
2279
2280         $U->simplereq(
2281             'open-ils.actor',
2282             'open-ils.actor.history.circ.clear',
2283             $self->editor->authtoken,
2284             $options
2285         );
2286     }
2287
2288     return;
2289 }
2290
2291 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
2292 sub load_myopac_hold_history {
2293     my $self = shift;
2294     my $e = $self->editor;
2295     my $ctx = $self->ctx;
2296     my $limit = $self->cgi->param('limit') || 15;
2297     my $offset = $self->cgi->param('offset') || 0;
2298     $ctx->{hold_history_limit} = $limit;
2299     $ctx->{hold_history_offset} = $offset;
2300
2301     my $hold_ids = $e->json_query({
2302         select => {
2303             au => [{
2304                 column => 'id',
2305                 transform => 'action.usr_visible_holds',
2306                 result_field => 'id'
2307             }]
2308         },
2309         from => 'au',
2310         where => {id => $e->requestor->id}
2311     });
2312
2313     my $holds_object = $self->fetch_user_holds([map { $_->{id} } @$hold_ids], 0, 1, 0, $limit, $offset);
2314     if($holds_object->{holds}) {
2315         $ctx->{holds} = $holds_object->{holds};
2316     }
2317     $ctx->{hold_history_ids} = $holds_object->{all_ids};
2318
2319     return Apache2::Const::OK;
2320 }
2321
2322 sub load_myopac_payment_form {
2323     my $self = shift;
2324     my $r;
2325     my $e = $self->editor;
2326
2327     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2328
2329     if ( ! $self->cgi->param('last_chance')) { # only do this once
2330         if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'Stripe') {
2331             if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.enabled')) {
2332                 my $skey = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.secretkey');
2333                 my $currency = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.stripe.currency');
2334                 my $stripe = Business::Stripe->new(-api_key => $skey);
2335                 my $intent = $stripe->api('post', 'payment_intents',
2336                     amount                => $self->ctx->{fines}->{balance_owed} * 100,
2337                     currency              => $currency || 'usd',
2338                     description           => 'User Database ID: ' . $self->ctx->{user}->id
2339                 );
2340                 if ($stripe->success) {
2341                     $self->ctx->{stripe_client_secret} = $stripe->success()->{client_secret};
2342                 } else {
2343                     $logger->error('Error initializing Stripe: ' . Dumper($stripe->error));
2344                     $self->ctx->{cc_configuration_error} = 1;
2345                 }
2346             }
2347         } elsif ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.default') eq 'SmartPAY') {
2348             if ($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.enabled')) {
2349                 my $location_id =  CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.location_id'));
2350                 $self->ctx->{smartpay_locationid} = $location_id;
2351                 my $customer_id =  CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.customer_id'));
2352                 $self->ctx->{smartpay_customerid} = $customer_id;
2353                 my $login = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.login'));
2354                 my $password = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.password'));
2355                 my $api_key = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.api_key'));
2356                 my $server = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.server'));
2357                 my $port = CGI::escapeHTML($self->ctx->{get_org_setting}->($e->requestor->home_ou, 'credit.processor.smartpay.port'));
2358                 my $base_target = "https://$server";
2359                 $base_target .= ":$port" if $port;
2360                 $base_target .= "/SMARTPAYAPI/WEBSMARTPAY.dll";
2361                 
2362                 # first api call
2363                 my $target = $base_target . "?RequestSessionKey";
2364                 $target .= "&CustomerID=$customer_id";
2365                 $target .= "&LocationID=$location_id";
2366                 $target .= "&UserName=$login";
2367                 $target .= "&Password=$password";
2368                 $target .= "&APIKey=$api_key";
2369
2370                 my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2371                 #$logger->error('SmartPAY debug, cache_args = ' . Dumper($cache_args) );
2372
2373                 # generate a temporary cache token for our secret
2374                 my $token = 'smartpay_' . md5_hex($$ . time() . rand());
2375                 $target .= "&Secret=$token";
2376
2377                 #$logger->error('SmartPAY debug, target= $target ' . Dumper($target) );
2378
2379                 my $ua = new LWP::UserAgent;
2380
2381                 # there has been API flux with whether to send API-Key and Secret as HTTP headers or URL params
2382                 #my $req = GET($target, 'API-Key' => "$api_key", 'Secret' => "$token");
2383                 my $req = GET($target);
2384                 my $response = $ua->request($req);
2385
2386                 if ($response->is_success() && $response->content() !~ /HTML/) {
2387                     $logger->info('SmartPAY initialized for ' . $self->editor->authtoken);
2388
2389                     my $session_key = $response->content();
2390
2391                     # we'll test this secret key again in the create payment method
2392                     my $cache_args = {
2393                         user => $self->ctx->{user}->id,
2394                         session_key => $session_key
2395                     };
2396                     my $cache = OpenSRF::Utils::Cache->new('global');
2397                     $cache->put_cache($token, $cache_args, 300);
2398
2399                     # this will be for our follow-up call client-side
2400
2401                     $self->ctx->{smartpay_target} = $base_target . '?GetCreditForm';
2402                     $self->ctx->{smartpay_target} .= '&SessionKey=' . $session_key;
2403                     $self->ctx->{smartpay_target} .= "&CustomerID=$customer_id";
2404                     $self->ctx->{smartpay_target} .= "&LocationID=$location_id";
2405                     $self->ctx->{smartpay_target} .= '&PatronID=' . $self->ctx->{user}->id; # $e->requestor->id;
2406                     $self->ctx->{smartpay_target} .= '&InvNum=1234';
2407                     $self->ctx->{smartpay_target} .= '&Amount=' . $self->ctx->{fines}->{balance_owed};
2408                     $self->ctx->{smartpay_target} .= '&URLPostBack=' . CGI::escapeHTML( $self->ctx->{hostname} );
2409                     #$self->ctx->{smartpay_target} .= '&ScriptPostBack=' .  CGI::escapeHTML('/cgi-bin/offline/echo1.pl');
2410                     $self->ctx->{smartpay_target} .= '&URLReturn=' .  CGI::escapeHTML( $self->ctx->{opac_root} . '/myopac/main_pay_init' );
2411                     $self->ctx->{smartpay_target} .= '&URLCancel=' .  CGI::escapeHTML( 'https://' . $self->ctx->{hostname} . $self->ctx->{opac_root} . '/myopac/charges');
2412                     $self->ctx->{smartpay_target} .= '&UserName=&Password=&Field1=smartpay&Field2=&Field3=&ItemsData=';
2413
2414                 } else {
2415                     my $error = $response->content();
2416                     $error =~ s/[\r\n]//g;
2417                     $logger->error("Error initializing SmartPAY: $error");
2418                     $self->ctx->{cc_configuration_error} = 1;
2419                 }
2420             }
2421         }
2422     }
2423
2424     if ($r) { return $r; }
2425     $r = $self->prepare_extended_user_info and return $r;
2426
2427     return Apache2::Const::OK;
2428 }
2429
2430 # TODO: add other filter options as params/configs/etc.
2431 sub load_myopac_payments {
2432     my $self = shift;
2433     my $limit = $self->cgi->param('limit') || 20;
2434     my $offset = $self->cgi->param('offset') || 0;
2435     my $e = $self->editor;
2436
2437     $self->ctx->{payment_history_limit} = $limit;
2438     $self->ctx->{payment_history_offset} = $offset;
2439
2440     my $args = {};
2441     $args->{limit} = $limit if $limit;
2442     $args->{offset} = $offset if $offset;
2443
2444     if (my $max_age = $self->ctx->{get_org_setting}->(
2445         $e->requestor->home_ou, "opac.payment_history_age_limit"
2446     )) {
2447         my $min_ts = DateTime->now(
2448             "time_zone" => DateTime::TimeZone->new("name" => "local"),
2449         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
2450
2451         $logger->info("XXX min_ts: $min_ts");
2452         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
2453     }
2454
2455     $self->ctx->{payments} = $U->simplereq(
2456         'open-ils.actor',
2457         'open-ils.actor.user.payments.retrieve.atomic',
2458         $e->authtoken, $e->requestor->id, $args);
2459
2460     return Apache2::Const::OK;
2461 }
2462
2463 # 1. caches the form parameters
2464 # 2. loads the credit card payment "Processing..." page
2465 sub load_myopac_pay_init {
2466     my $self = shift;
2467     my $cache = OpenSRF::Utils::Cache->new('global');
2468
2469     my @payment_xacts = ($self->cgi->param('xact'), $self->cgi->param('xact_misc'));
2470
2471     if (!@payment_xacts) {
2472         # for consistency with load_myopac_payment_form() and
2473         # to preserve backwards compatibility, if no xacts are
2474         # selected, assume all (applicable) transactions are wanted.
2475         my $stat = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]);
2476         return $stat if $stat;
2477         @payment_xacts =
2478             map { $_->{xact}->id } (
2479                 @{$self->ctx->{fines}->{circulation}},
2480                 @{$self->ctx->{fines}->{grocery}}
2481         );
2482     }
2483
2484     return $self->generic_redirect unless @payment_xacts;
2485
2486     my $cc_args = {"where_process" => 1};
2487
2488     $cc_args->{$_} = $self->cgi->param($_) for (qw/
2489         number cvv2 expire_year expire_month billing_first
2490         billing_last billing_address billing_city billing_state
2491         billing_zip stripe_payment_intent stripe_client_secret
2492     /);
2493
2494     # mapping SmartPAY CGI parameters
2495     if ($self->cgi->param('Result')) {
2496         $cc_args->{smartpay_result} = $self->cgi->param('Result');
2497     }
2498     if ($self->cgi->param('Secret')) {
2499         $cc_args->{smartpay_secret} = $self->cgi->param('Secret');
2500     }
2501     if ($self->cgi->param('CCNumber')) {
2502         $cc_args->{number} = $self->cgi->param('CCNumber');
2503     }
2504
2505     my $cache_args = {
2506         cc_args => $cc_args,
2507         user => $self->ctx->{user}->id,
2508         xacts => \@payment_xacts
2509     };
2510
2511     # generate a temporary cache token and cache the form data
2512     my $token = md5_hex($$ . time() . rand());
2513     $cache->put_cache($token, $cache_args, 30);
2514
2515     $logger->info("tpac caching payment info with token $token and xacts [@payment_xacts]");
2516
2517     # after we render the processing page, we quickly redirect to submit
2518     # the actual payment.  The refresh url contains the payment token.
2519     # It also contains the list of xact IDs, which allows us to clear the
2520     # cache at the earliest possible time while leaving a trace of which
2521     # transactions we were processing, so the UI can bring the user back
2522     # to the payment form w/ the same xacts if the payment fails.
2523
2524     my $refresh = "1; url=main_pay/$token?xact=" . pop(@payment_xacts);
2525     $refresh .= ";xact=$_" for @payment_xacts;
2526     $self->ctx->{refresh} = $refresh;
2527
2528     return Apache2::Const::OK;
2529 }
2530
2531 # retrieve the cached CC payment info and send off for processing
2532 sub load_myopac_pay {
2533     my $self = shift;
2534     my $token = $self->ctx->{page_args}->[0];
2535     return Apache2::Const::HTTP_BAD_REQUEST unless $token;
2536
2537     my $cache = OpenSRF::Utils::Cache->new('global');
2538     my $cache_args = $cache->get_cache($token);
2539     $cache->delete_cache($token);
2540
2541     # this page is loaded immediately after the token is created.
2542     # if the cached data is not there, it's because of an invalid
2543     # token (or cache failure) and not because of a timeout.
2544     return Apache2::Const::HTTP_BAD_REQUEST unless $cache_args;
2545
2546     my @payment_xacts = @{$cache_args->{xacts}};
2547     my $cc_args = $cache_args->{cc_args};
2548
2549     # as an added security check, verify the user submitting
2550     # the form is the same as the user whose data was cached
2551     return Apache2::Const::HTTP_BAD_REQUEST unless
2552         $cache_args->{user} == $self->ctx->{user}->id;
2553
2554     $logger->info("tpac paying fines with token $token and xacts [@payment_xacts]");
2555
2556     my $r;
2557     $r = $self->prepare_fines(undef, undef, \@payment_xacts) and return $r;
2558
2559     # balance_owed is computed specifically from the fines we're paying
2560     if ($self->ctx->{fines}->{balance_owed} <= 0) {
2561         $logger->info("tpac can't pay non-positive balance. xacts selected: [@payment_xacts]");
2562         return Apache2::Const::HTTP_BAD_REQUEST;
2563     }
2564
2565     my $args = {
2566         "cc_args" => $cc_args,
2567         "userid" => $self->ctx->{user}->id,
2568         "payment_type" => "credit_card_payment",
2569         "payments" => $self->prepare_fines_for_payment  # should be safe after self->prepare_fines
2570     };
2571
2572     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
2573         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
2574     );
2575
2576     $self->ctx->{"payment_response"} = $resp;
2577
2578     unless ($resp->{"textcode"}) {
2579         $self->ctx->{printable_receipt} = $U->simplereq(
2580         "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2581         $self->editor->authtoken, $resp->{payments}
2582         );
2583     }
2584
2585     return Apache2::Const::OK;
2586 }
2587
2588 sub load_myopac_receipt_print {
2589     my $self = shift;
2590
2591     $self->ctx->{printable_receipt} = $U->simplereq(
2592     "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
2593     $self->editor->authtoken, [$self->cgi->param("payment")]
2594     );
2595
2596     return Apache2::Const::OK;
2597 }
2598
2599 sub load_myopac_receipt_email {
2600     my $self = shift;
2601
2602     # The following ML method doesn't actually check whether the user in
2603     # question has an email address, so we do.
2604     if ($self->ctx->{user}->email) {
2605         $self->ctx->{email_receipt_result} = $U->simplereq(
2606         "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
2607         $self->editor->authtoken, [$self->cgi->param("payment")]
2608         );
2609     } else {
2610         $self->ctx->{email_receipt_result} =
2611             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
2612     }
2613
2614     return Apache2::Const::OK;
2615 }
2616
2617 sub prepare_fines {
2618     my ($self, $limit, $offset, $id_list) = @_;
2619
2620     # XXX TODO: check for failure after various network calls
2621
2622     # It may be unclear, but this result structure lumps circulation and
2623     # reservation fines together, and keeps grocery fines separate.
2624     $self->ctx->{"fines"} = {
2625         "circulation" => [],
2626         "grocery" => [],
2627         "total_paid" => 0,
2628         "total_owed" => 0,
2629         "balance_owed" => 0
2630     };
2631
2632     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
2633
2634     # TODO: This should really be a ML call, but the existing calls
2635     # return an excessive amount of data and don't offer streaming
2636
2637     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
2638
2639     my $req = $cstore->request(
2640         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
2641         {
2642             usr => $self->editor->requestor->id,
2643             balance_owed => {'!=' => 0},
2644             ($id_list && @$id_list ? ("id" => $id_list) : ()),
2645         },
2646         {
2647             flesh => 4,
2648             flesh_fields => {
2649                 mobts => [qw/grocery circulation reservation/],
2650                 bresv => ['target_resource_type'],
2651                 brt => ['record'],
2652                 mg => ['billings'],
2653                 mb => ['btype'],
2654                 circ => ['target_copy'],
2655                 acp => ['call_number'],
2656                 acn => ['record']
2657             },
2658             order_by => { mobts => 'xact_start' },
2659             %paging
2660         }
2661     );
2662
2663     # Collect $$ amounts from each transaction for summing below.
2664     my (@paid_amounts, @owed_amounts, @balance_amounts);
2665
2666     while(my $resp = $req->recv) {
2667         my $mobts = $resp->content;
2668         my $circ = $mobts->circulation;
2669
2670         my $last_billing;
2671         if($mobts->grocery) {
2672             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
2673             $last_billing = pop(@billings);
2674         }
2675
2676         push(@paid_amounts, $mobts->total_paid);
2677         push(@owed_amounts, $mobts->total_owed);
2678         push(@balance_amounts, $mobts->balance_owed);
2679
2680         my $marc_xml = undef;
2681         if ($mobts->xact_type eq 'reservation' and
2682             $mobts->reservation->target_resource_type->record) {
2683             $marc_xml = XML::LibXML->new->parse_string(
2684                 $mobts->reservation->target_resource_type->record->marc
2685             );
2686         } elsif ($mobts->xact_type eq 'circulation' and
2687             $circ->target_copy->call_number->id != -1) {
2688             $marc_xml = XML::LibXML->new->parse_string(
2689                 $circ->target_copy->call_number->record->marc
2690             );
2691         }
2692
2693         push(
2694             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
2695             {
2696                 xact => $mobts,
2697                 last_grocery_billing => $last_billing,
2698                 marc_xml => $marc_xml
2699             }
2700         );
2701     }
2702
2703     $cstore->kill_me;
2704
2705     $self->ctx->{"fines"}->{total_paid}   = $U->fpsum(@paid_amounts);
2706     $self->ctx->{"fines"}->{total_owed}   = $U->fpsum(@owed_amounts);
2707     $self->ctx->{"fines"}->{balance_owed} = $U->fpsum(@balance_amounts);
2708
2709     return;
2710 }
2711
2712 sub prepare_fines_for_payment {
2713     # This assumes $self->prepare_fines has already been run
2714     my ($self) = @_;
2715
2716     my @results = ();
2717     if ($self->ctx->{fines}) {
2718         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
2719             @{$self->ctx->{fines}->{circulation}},
2720             @{$self->ctx->{fines}->{grocery}}
2721         );
2722     }
2723
2724     return \@results;
2725 }
2726
2727 sub load_myopac_main {
2728     my $self = shift;
2729     my $limit = $self->cgi->param('limit') || 0;
2730     my $offset = $self->cgi->param('offset') || 0;
2731     $self->ctx->{search_ou} = $self->_get_search_lib();
2732     $self->ctx->{user}->notes(
2733         $self->editor->search_actor_usr_message({
2734             usr => $self->ctx->{user}->id,
2735             pub => 't'
2736         })
2737     );
2738     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
2739 }
2740
2741 sub load_myopac_update_email {
2742     my $self = shift;
2743     my $e = $self->editor;
2744     my $ctx = $self->ctx;
2745     my $email = $self->cgi->param('email') || '';
2746     my $current_pw = $self->cgi->param('current_pw') || '';
2747
2748     # needed for most up-to-date email address
2749     if (my $r = $self->prepare_extended_user_info) { return $r };
2750
2751     return Apache2::Const::OK
2752         unless $self->cgi->request_method eq 'POST';
2753
2754     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
2755         $ctx->{invalid_email} = $email;
2756         return Apache2::Const::OK;
2757     }
2758
2759     my $stat = $U->simplereq(
2760         'open-ils.actor',
2761         'open-ils.actor.user.email.update',
2762         $e->authtoken, $email, $current_pw);
2763
2764     if($U->event_equals($stat, 'INCORRECT_PASSWORD')) {
2765         $ctx->{password_incorrect} = 1;
2766         return Apache2::Const::OK;
2767     }
2768
2769     unless ($self->cgi->param("redirect_to")) {
2770         my $url = $self->apache->unparsed_uri;
2771         $url =~ s/update_email/prefs/;
2772
2773         return $self->generic_redirect($url);
2774     }
2775
2776     return $self->generic_redirect;
2777 }
2778
2779 sub load_myopac_update_username {
2780     my $self = shift;
2781     my $e = $self->editor;
2782     my $ctx = $self->ctx;
2783     my $username = $self->cgi->param('username') || '';
2784     my $current_pw = $self->cgi->param('current_pw') || '';
2785
2786     $self->prepare_extended_user_info;
2787
2788     my $allow_change = 1;
2789     my $regex_check;
2790     my $lock_usernames = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.lock_usernames');
2791     if(defined($lock_usernames) and $lock_usernames == 1) {
2792         # Policy says no username changes
2793         $allow_change = 0;
2794     } else {
2795         # We want this further down.
2796         $regex_check = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.barcode_regex');
2797         my $username_unlimit = $self->ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.unlimit_usernames');
2798         if(!$username_unlimit) {
2799             if(!$regex_check) {
2800                 # Default is "starts with a number"
2801                 $regex_check = '^\d+';
2802             }
2803             # You already have a username?
2804             if($regex_check and $self->ctx->{user}->usrname !~ /$regex_check/) {
2805                 $allow_change = 0;
2806             }
2807         }
2808     }
2809     if(!$allow_change) {
2810         my $url = $self->apache->unparsed_uri;
2811         $url =~ s/update_username/prefs/;
2812
2813         return $self->generic_redirect($url);
2814     }
2815
2816     return Apache2::Const::OK
2817         unless $self->cgi->request_method eq 'POST';
2818
2819     unless($username and $username !~ /\s/) { # any other username restrictions?
2820         $ctx->{invalid_username} = $username;
2821         return Apache2::Const::OK;
2822     }
2823
2824     # New username can't look like a barcode if we have a barcode regex
2825     if($regex_check and $username =~ /$regex_check/) {
2826         $ctx->{invalid_username} = $username;
2827         return Apache2::Const::OK;
2828     }
2829
2830     # New username has to look like a username if we have a username regex
2831     $regex_check = $ctx->{get_org_setting}->($e->requestor->home_ou, 'opac.username_regex');
2832     if($regex_check and $username !~ /$regex_check/) {
2833         $ctx->{invalid_username} = $username;
2834         return Apache2::Const::OK;
2835     }
2836
2837     if($username ne $e->requestor->usrname) {
2838
2839         my $evt = $U->simplereq(
2840             'open-ils.actor',
2841             'open-ils.actor.user.username.update',
2842             $e->authtoken, $username, $current_pw);
2843
2844         if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2845             $ctx->{password_incorrect} = 1;
2846             return Apache2::Const::OK;
2847         }
2848
2849         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
2850             $ctx->{username_exists} = $username;
2851             return Apache2::Const::OK;
2852         }
2853     }
2854
2855     my $url = $self->apache->unparsed_uri;
2856     $url =~ s/update_username/prefs/;
2857
2858     return $self->generic_redirect($url);
2859 }
2860
2861 sub load_myopac_update_locale {
2862     my $self = shift;
2863     my $e = $self->editor;
2864     my $ctx = $self->ctx;
2865     my $lang = $self->cgi->param('pref_lang') || '';
2866     my $current_pw = $self->cgi->param('current_pw') || '';
2867
2868     $self->prepare_extended_user_info;
2869
2870     my $locs = $U->simplereq(
2871         'open-ils.cstore',
2872         "open-ils.cstore.direct.config.i18n_locale.search.atomic", 
2873         { "code" => { "!=" => undef } }
2874     );
2875
2876     my %user_locales;
2877     foreach my $l (@$locs) { $user_locales{$l->code} = $l->name; }
2878     $self->ctx->{i18n_locales} = \%user_locales; 
2879
2880     return Apache2::Const::OK
2881         unless $self->cgi->request_method eq 'POST';
2882
2883     if($lang ne $e->requestor->locale) {
2884         my $evt = $U->simplereq(
2885             'open-ils.actor',
2886             'open-ils.actor.user.locale.update',
2887             $e->authtoken, $lang, $current_pw);
2888
2889         if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2890             $ctx->{password_incorrect} = 1;
2891             return Apache2::Const::OK;
2892         }
2893     }
2894
2895     my $url = $self->apache->unparsed_uri;
2896     $url =~ s/update_locale/prefs/;
2897
2898     return $self->generic_redirect($url);
2899 }
2900
2901 sub load_myopac_update_password {
2902     my $self = shift;
2903     my $e = $self->editor;
2904     my $ctx = $self->ctx;
2905
2906     return Apache2::Const::OK
2907         unless $self->cgi->request_method eq 'POST';
2908
2909     my $current_pw = $self->cgi->param('current_pw') || '';
2910     my $new_pw = $self->cgi->param('new_pw') || '';
2911     my $new_pw2 = $self->cgi->param('new_pw2') || '';
2912
2913     unless($new_pw eq $new_pw2) {
2914         $ctx->{password_nomatch} = 1;
2915         return Apache2::Const::OK;
2916     }
2917
2918     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
2919
2920     if(!$pw_regex) {
2921         # This regex duplicates the JSPac's default "digit, letter, and 7 characters" rule
2922         $pw_regex = '(?=.*\d+.*)(?=.*[A-Za-z]+.*).{7,}';
2923     }
2924
2925     if($pw_regex and $new_pw !~ /$pw_regex/) {
2926         $ctx->{password_invalid} = 1;
2927         return Apache2::Const::OK;
2928     }
2929
2930     my $evt = $U->simplereq(
2931         'open-ils.actor',
2932         'open-ils.actor.user.password.update',
2933         $e->authtoken, $new_pw, $current_pw);
2934
2935
2936     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
2937         $ctx->{password_incorrect} = 1;
2938         return Apache2::Const::OK;
2939     }
2940
2941     my $url = $self->apache->unparsed_uri;
2942     $url =~ s/update_password/prefs/;
2943
2944     return $self->generic_redirect($url);
2945 }
2946
2947 sub _update_bookbag_metadata {
2948     my ($self, $bookbag) = @_;
2949
2950     $bookbag->name($self->cgi->param("name"));
2951     $bookbag->description($self->cgi->param("description"));
2952
2953     return 1 if $self->editor->update_container_biblio_record_entry_bucket($bookbag);
2954     return 0;
2955 }
2956
2957 sub _get_lists_per_page {
2958     my $self = shift;
2959
2960     if($self->editor->requestor) {
2961         $self->timelog("Checking for opac.lists_per_page preference");
2962         # See if the user has a lists per page preference
2963         my $ipp = $self->editor->search_actor_user_setting({
2964             usr => $self->editor->requestor->id,
2965             name => 'opac.lists_per_page'
2966         })->[0];
2967         $self->timelog("Got opac.lists_per_page preference");
2968         return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2969     }
2970     return 10; # default
2971 }
2972
2973 sub _get_items_per_page {
2974     my $self = shift;
2975
2976     if($self->editor->requestor) {
2977         $self->timelog("Checking for opac.list_items_per_page preference");
2978         # See if the user has a list items per page preference
2979         my $ipp = $self->editor->search_actor_user_setting({
2980             usr => $self->editor->requestor->id,
2981             name => 'opac.list_items_per_page'
2982         })->[0];
2983         $self->timelog("Got opac.list_items_per_page preference");
2984         return OpenSRF::Utils::JSON->JSON2perl($ipp->value) if $ipp;
2985     }
2986     return 10; # default
2987 }
2988
2989 sub load_myopac_bookbags {
2990     my $self = shift;
2991     my $e = $self->editor;
2992     my $ctx = $self->ctx;
2993     my $limit = $self->_get_lists_per_page || 10;
2994     my $offset = $self->cgi->param('offset') || 0;
2995
2996     $ctx->{bookbags_limit} = $limit;
2997     $ctx->{bookbags_offset} = $offset;
2998
2999     # for list item pagination
3000     my $item_limit = $self->_get_items_per_page;
3001     my $item_page = $self->cgi->param('item_page') || 1;
3002     my $item_offset = ($item_page - 1) * $item_limit;
3003     $ctx->{bookbags_item_page} = $item_page;
3004
3005     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3006     $e->xact_begin; # replication...
3007
3008     my $rv = $self->load_mylist;
3009     unless($rv eq Apache2::Const::OK) {
3010         $e->rollback;
3011         return $rv;
3012     }
3013
3014     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket(
3015         [
3016             {owner => $e->requestor->id, btype => 'bookbag'}, {
3017                 order_by => {cbreb => 'name'},
3018                 limit => $limit,
3019                 offset => $offset
3020             }
3021         ],
3022         {substream => 1}
3023     );
3024
3025     if(!$ctx->{bookbags}) {
3026         $e->rollback;
3027         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3028     }
3029
3030     # We load the user prefs to get their default bookbag.
3031     $self->_load_user_with_prefs;
3032
3033     # We also want a total count of the user's bookbags.
3034     my $q = {
3035         'select' => { 'cbreb' => [ { 'column' => 'id', 'transform' => 'count', 'aggregate' => 'true', 'alias' => 'count' } ] },
3036         'from' => 'cbreb',
3037         'where' => { 'btype' => 'bookbag', 'owner' => $self->ctx->{user}->id }
3038     };
3039     my $r = $e->json_query($q);
3040     $ctx->{bookbag_count} = $r->[0]->{'count'};
3041
3042     # If the user wants a specific bookbag's items, load them.
3043
3044     if ($self->cgi->param("bbid")) {
3045         my ($bookbag) =
3046             grep { $_->id eq $self->cgi->param("bbid") } @{$ctx->{bookbags}};
3047
3048         if ($bookbag) {
3049             my $query = $self->_prepare_bookbag_container_query(
3050                 $bookbag->id, $sorter, $modifier
3051             );
3052
3053             # Calculate total count of the items in selected bookbag.
3054             # This total includes record entries that have no assets available.
3055             my $bb_search_results = $U->simplereq(
3056                 "open-ils.search", "open-ils.search.biblio.multiclass.query",
3057                 {"limit" => 1, "offset" => 0}, $query
3058             ); # we only need the count, so do the actual search with limit=1
3059
3060             if ($bb_search_results) {
3061                 $ctx->{bb_item_count} = $bb_search_results->{count};
3062             } else {
3063                 $logger->warn("search failed in load_myopac_bookbags()");
3064                 $ctx->{bb_item_count} = 0; # fallback value
3065             }
3066
3067             #calculate page count
3068             $ctx->{bb_page_count} = int ((($ctx->{bb_item_count} - 1) / $item_limit) + 1);
3069
3070             if ( ($self->cgi->param("action") || '') eq "editmeta") {
3071                 if (!$self->_update_bookbag_metadata($bookbag))  {
3072                     $e->rollback;
3073                     return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3074                 } else {
3075                     $e->commit;
3076                     my $url = $self->ctx->{opac_root} . '/myopac/lists?bbid=' .
3077                         $bookbag->id;
3078
3079                     foreach my $param (('loc', 'qtype', 'query', 'sort', 'offset', 'limit')) {
3080                         if ($self->cgi->param($param)) {
3081                             my @vals = $self->cgi->param($param);
3082                             $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3083                         }
3084                     }
3085
3086                     return $self->generic_redirect($url);
3087                 }
3088             }
3089
3090             # we're done with our CStoreEditor.  Rollback here so
3091             # later calls don't cause a timeout, resulting in a
3092             # transaction rollback under the covers.
3093             $e->rollback;
3094
3095
3096             # For list items pagination
3097             my $args = {
3098                 "limit" => $item_limit,
3099                 "offset" => $item_offset
3100             };
3101
3102             my $items = $U->bib_container_items_via_search($bookbag->id, $query, $args)
3103                 or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3104
3105             # capture pref_ou for callnumber filter/display
3106             $ctx->{pref_ou} = $self->_get_pref_lib() || $ctx->{search_ou};
3107
3108             # search for local callnumbers for display
3109             my $focus_ou = $ctx->{physical_loc} || $ctx->{pref_ou};
3110
3111             my (undef, @recs) = $self->get_records_and_facets(
3112                 [ map {$_->target_biblio_record_entry->id} @$items ],
3113                 undef,
3114                 {
3115                     flesh => '{mra,holdings_xml,acp,exclude_invisible_acn}',
3116                     flesh_depth => 1,
3117                     site => $ctx->{get_aou}->($focus_ou)->shortname,
3118                     pref_lib => $ctx->{pref_ou}
3119                 }
3120             );
3121
3122             $ctx->{bookbags_marc_xml}{$_->{id}} = $_->{marc_xml} for @recs;
3123
3124             $bookbag->items($items);
3125         }
3126     }
3127
3128     # If we have add_rec, we got here from the "Add to new list"
3129     # or "See all" popmenu items.
3130     if (my $add_rec = $self->cgi->param('add_rec')) {
3131         $self->ctx->{add_rec} = $add_rec;
3132         # But not in the staff client, 'cause that breaks things.
3133         unless ($self->ctx->{is_staff}) {
3134             # allow caller to provide the where_from in cases where
3135             # the referer is an intermediate error page
3136             if ($self->cgi->param('where_from')) {
3137                 $self->ctx->{where_from} = $self->cgi->param('where_from');
3138             } else {
3139                 $self->ctx->{where_from} = $self->ctx->{referer};
3140                 if ( my $anchor = $self->cgi->param('anchor') ) {
3141                     $self->ctx->{where_from} =~ s/#.*|$/#$anchor/;
3142                 }
3143             }
3144         }
3145     }
3146
3147     # this rollback may be a dupe, but that's OK because
3148     # cstoreditor ignores dupe rollbacks
3149     $e->rollback;
3150
3151     return Apache2::Const::OK;
3152 }
3153
3154
3155 # actions are create, delete, show, hide, rename, add_rec, delete_item, place_hold, print, email
3156 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
3157 sub load_myopac_bookbag_update {
3158     my ($self, $action, $list_id, @hold_recs) = @_;
3159     my $e = $self->editor;
3160     my $cgi = $self->cgi;
3161
3162     # save_notes is effectively another action, but is passed in a separate
3163     # CGI parameter for what are really just layout reasons.
3164     $action = 'save_notes' if $cgi->param('save_notes');
3165     $action ||= $cgi->param('action');
3166
3167     $list_id ||= $cgi->param('list') || $cgi->param('bbid');
3168
3169     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
3170     my @selected_item = $cgi->param('selected_item');
3171     my $shared = $cgi->param('shared');
3172     my $move_cart = $cgi->param('move_cart');
3173     my $name = $cgi->param('name');
3174     my $description = $cgi->param('description');
3175     my $success = 0;
3176     my $list;
3177
3178     # bail out if user is attempting an action that requires
3179     # that at least one list item be selected
3180     if ((scalar(@selected_item) == 0) && (scalar(@hold_recs) == 0) &&
3181         ($action eq 'place_hold' || $action eq 'print' ||
3182          $action eq 'email' || $action eq 'del_item')) {
3183         my $url = $self->ctx->{referer};
3184         $url .= ($url =~ /\?/ ? '&' : '?') . 'list_none_selected=1' unless $url =~ /list_none_selected/;
3185         return $self->generic_redirect($url);
3186     }
3187
3188     # This url intentionally leaves off the edit_notes parameter, but
3189     # may need to add some back in for paging.
3190
3191     my $url = $self->ctx->{proto} . "://" . $self->ctx->{hostname} .
3192         $self->ctx->{opac_root} . "/myopac/lists?";
3193
3194     foreach my $param (('loc', 'qtype', 'query', 'sort')) {
3195         if ($cgi->param($param)) {
3196             my @vals = $cgi->param($param);
3197             $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3198         }
3199     }
3200
3201     if ($action eq 'create') {
3202
3203         if ($name) {
3204             $list = Fieldmapper::container::biblio_record_entry_bucket->new;
3205             $list->name($name);
3206             $list->description($description);
3207             $list->owner($e->requestor->id);
3208             $list->btype('bookbag');
3209             $list->pub($shared ? 't' : 'f');
3210             $success = $U->simplereq('open-ils.actor',
3211                 'open-ils.actor.container.create', $e->authtoken, 'biblio', $list);
3212             if (ref($success) ne 'HASH') {
3213                 $list_id = (ref($success)) ? $success->id : $success;
3214                 if (scalar @add_rec) {
3215                     foreach my $add_rec (@add_rec) {
3216                         my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3217                         $item->bucket($list_id);
3218                         $item->target_biblio_record_entry($add_rec);
3219                         $success = $U->simplereq('open-ils.actor',
3220                                                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3221                         last unless $success;
3222                     }
3223                 }
3224                 if ($move_cart) {
3225                     my ($cache_key, $list) = $self->fetch_mylist(0, 1);
3226                     foreach my $add_rec (@$list) {
3227                         my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3228                         $item->bucket($list_id);
3229                         $item->target_biblio_record_entry($add_rec);
3230                         $success = $U->simplereq('open-ils.actor',
3231                                                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3232                         last unless $success;
3233                     }
3234                     $self->clear_anon_cache;
3235                 }
3236             }
3237             $url = $cgi->param('where_from') if ($success && $cgi->param('where_from'));
3238
3239         } else { # no name
3240             $self->ctx->{bucket_failure_noname} = 1;
3241         }
3242
3243     } elsif($action eq 'place_hold') {
3244
3245         # @hold_recs comes from anon lists redirect; selected_items comes from existing buckets
3246         my $from_basket = scalar(@hold_recs);
3247         unless (@hold_recs) {
3248             if (@selected_item) {
3249                 my $items = $e->search_container_biblio_record_entry_bucket_item({id => \@selected_item});
3250                 @hold_recs = map { $_->target_biblio_record_entry } @$items;
3251             }
3252         }
3253
3254         return Apache2::Const::OK unless @hold_recs;
3255         $logger->info("placing holds from list page on: @hold_recs");
3256
3257         my $url = $self->ctx->{opac_root} . '/place_hold?hold_type=T';
3258         $url .= ';hold_target=' . $_ for @hold_recs;
3259         $url .= ';from_basket=1' if $from_basket;
3260         foreach my $param (('loc', 'qtype', 'query')) {
3261             if ($cgi->param($param)) {
3262                 my @vals = $cgi->param($param);
3263                 $url .= ";$param=" . uri_escape_utf8($_) foreach @vals;
3264             }
3265         }
3266         return $self->generic_redirect($url);
3267
3268     } elsif ($action eq 'print') {
3269         my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3270         $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3271         if (!$incoming_sort) {
3272             ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3273         }
3274         if (!$incoming_sort) {
3275             $incoming_sort = 'author';
3276         }
3277
3278         $incoming_sort =~ s/sort.*$//;
3279
3280         $self->ctx->{sort} = $incoming_sort;
3281         $self->ctx->{sort_dir} = $sort_dir;
3282
3283         my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3284         my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3285         my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3286         return $self->load_mylist_print($temp_cache_key);
3287     } elsif ($action eq 'email') {
3288         my ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('sort');
3289         $sort_dir = $self->cgi->param('sort_dir') if $self->cgi->param('sort_dir');
3290         if (!$incoming_sort) {
3291             ($incoming_sort,$sort_dir) = $self->_get_bookbag_sort_params('anonsort');
3292         }
3293         if (!$incoming_sort) {
3294             $incoming_sort = 'author';
3295         }
3296
3297         $incoming_sort =~ s/sort.*$//;
3298
3299         $self->ctx->{sort} = $incoming_sort;
3300         $self->ctx->{sort_dir} = $sort_dir;
3301
3302         my $items = $self->editor->search_container_biblio_record_entry_bucket_item({id=>\@selected_item});
3303         my @bib_ids = map { $_->target_biblio_record_entry } @$items;
3304         my $temp_cache_key = $self->_stash_record_list_in_anon_cache(@bib_ids);
3305         return $self->load_mylist_email($temp_cache_key);
3306     } else {
3307
3308         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
3309
3310         return Apache2::Const::HTTP_BAD_REQUEST unless
3311             $list and $list->owner == $e->requestor->id;
3312     }
3313
3314     if($action eq 'delete') {
3315         $success = $U->simplereq('open-ils.actor',
3316             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
3317         if ($success) {
3318             # We check to see if we're deleting the user's default list.
3319             $self->_load_user_with_prefs;
3320             my $settings_map = $self->ctx->{user_setting_map};
3321             if ($$settings_map{'opac.default_list'} == $list_id) {
3322                 # We unset the user's opac.default_list setting.
3323                 $success = $U->simplereq(
3324                     'open-ils.actor',
3325                     'open-ils.actor.patron.settings.update',
3326                     $e->authtoken,
3327                     $e->requestor->id,
3328                     { 'opac.default_list' => 0 }
3329                 );
3330             }
3331         }
3332     } elsif($action eq 'show') {
3333         unless($U->is_true($list->pub)) {
3334             $list->pub('t');
3335             $success = $U->simplereq('open-ils.actor',
3336                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3337         }
3338
3339     } elsif($action eq 'hide') {
3340         if($U->is_true($list->pub)) {
3341             $list->pub('f');
3342             $success = $U->simplereq('open-ils.actor',
3343                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3344         }
3345
3346     } elsif($action eq 'rename') {
3347         if($name) {
3348             $list->name($name);
3349             $success = $U->simplereq('open-ils.actor',
3350                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
3351         }
3352
3353     } elsif($action eq 'add_rec') {
3354         foreach my $add_rec (@add_rec) {
3355             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
3356             $item->bucket($list_id);
3357             $item->target_biblio_record_entry($add_rec);
3358             $success = $U->simplereq('open-ils.actor',
3359                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
3360             last unless $success;
3361         }
3362         # Redirect back where we came from if we have an anchor parameter:
3363         if ( my $anchor = $cgi->param('anchor') && !$self->ctx->{is_staff}) {
3364             $url = $self->ctx->{referer};
3365             $url =~ s/#.*|$/#$anchor/;
3366         } elsif ($cgi->param('where_from')) {
3367             # Or, if we have a "where_from" parameter.
3368             $url = $cgi->param('where_from');
3369         }
3370     } elsif ($action eq 'del_item') {
3371         foreach (@selected_item) {
3372             $success = $U->simplereq(
3373                 'open-ils.actor',
3374                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
3375             );
3376             last unless $success;
3377         }
3378     } elsif ($action eq 'save_notes') {
3379         $success = $self->update_bookbag_item_notes;
3380         $url .= "&bbid=" . uri_escape_utf8($cgi->param("bbid")) if $cgi->param("bbid");
3381     } elsif ($action eq 'make_default') {
3382         $success = $U->simplereq(
3383             'open-ils.actor',
3384             'open-ils.actor.patron.settings.update',
3385             $e->authtoken,
3386             $list->owner,
3387             { 'opac.default_list' => $list_id }
3388         );
3389     } elsif ($action eq 'remove_default') {
3390         $success = $U->simplereq(
3391             'open-ils.actor',
3392             'open-ils.actor.patron.settings.update',
3393             $e->authtoken,
3394             $list->owner,
3395             { 'opac.default_list' => 0 }
3396         );
3397     }
3398
3399     return $self->generic_redirect($url) if $success;
3400
3401     $self->ctx->{where_from} = $cgi->param('where_from');
3402     $self->ctx->{bucket_action} = $action;
3403     $self->ctx->{bucket_action_failed} = 1;
3404     return Apache2::Const::OK;
3405 }
3406
3407 sub update_bookbag_item_notes {
3408     my ($self) = @_;
3409     my $e = $self->editor;
3410
3411     my @note_keys = grep /^note-\d+/, keys(%{$self->cgi->Vars});
3412     my @item_keys = grep /^item-\d+/, keys(%{$self->cgi->Vars});
3413
3414     # We're going to leverage an API call that's already been written to check
3415     # permissions appropriately.
3416
3417     my $a = create OpenSRF::AppSession("open-ils.actor");
3418     my $method = "open-ils.actor.container.item_note.cud";
3419
3420     for my $note_key (@note_keys) {
3421         my $note;
3422
3423         my $id = ($note_key =~ /(\d+)/)[0];
3424
3425         if (!($note =
3426             $e->retrieve_container_biblio_record_entry_bucket_item_note($id))) {
3427             my $event = $e->die_event;
3428             $self->apache->log->warn(
3429                 "error retrieving cbrebin id $id, got event " .
3430                 $event->{textcode}
3431             );
3432             $a->kill_me;
3433             $self->ctx->{bucket_action_event} = $event;
3434             return;
3435         }
3436
3437         if (length($self->cgi->param($note_key))) {
3438             $note->ischanged(1);
3439             $note->note($self->cgi->param($note_key));
3440         } else {
3441             $note->isdeleted(1);
3442         }
3443
3444         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3445
3446         if (defined $U->event_code($r)) {
3447             $self->apache->log->warn(
3448                 "attempt to modify cbrebin " . $note->id .
3449                 " returned event " .  $r->{textcode}
3450             );
3451             $e->rollback;
3452             $a->kill_me;
3453             $self->ctx->{bucket_action_event} = $r;
3454             return;
3455         }
3456     }
3457
3458     for my $item_key (@item_keys) {
3459         my $id = int(($item_key =~ /(\d+)/)[0]);
3460         my $text = $self->cgi->param($item_key);
3461
3462         chomp $text;
3463         next unless length $text;
3464
3465         my $note = new Fieldmapper::container::biblio_record_entry_bucket_item_note;
3466         $note->isnew(1);
3467         $note->item($id);
3468         $note->note($text);
3469
3470         my $r = $a->request($method, $e->authtoken, "biblio", $note)->gather(1);
3471
3472         if (defined $U->event_code($r)) {
3473             $self->apache->log->warn(
3474                 "attempt to create cbrebin for item " . $note->item .
3475                 " returned event " .  $r->{textcode}
3476             );
3477             $e->rollback;
3478             $a->kill_me;
3479             $self->ctx->{bucket_action_event} = $r;
3480             return;
3481         }
3482     }
3483
3484     $a->kill_me;
3485     return 1;   # success
3486 }
3487
3488 sub load_myopac_bookbag_print {
3489     my ($self) = @_;
3490
3491     my $id = int($self->cgi->param("list"));
3492
3493     my ($sorter, $modifier) = $self->_get_bookbag_sort_params("sort");
3494
3495     my $item_search =
3496         $self->_prepare_bookbag_container_query($id, $sorter, $modifier);
3497
3498     my $bbag;
3499
3500     # Get the bookbag object itself, assuming we're allowed to.
3501     if ($self->editor->allowed("VIEW_CONTAINER")) {
3502
3503         $bbag = $self->editor->retrieve_container_biblio_record_entry_bucket($id) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3504     } else {
3505         my $bookbags = $self->editor->search_container_biblio_record_entry_bucket(
3506             {
3507                 "id" => $id,
3508                 "-or" => {
3509                     "owner" => $self->editor->requestor->id,
3510                     "pub" => "t"
3511                 }
3512             }
3513         ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
3514
3515         $bbag = pop @$bookbags;
3516     }
3517
3518     # If we have a bookbag we're allowed to look at, issue the A/T event
3519     # to get CSV, passing as a user param that search query we built before.
3520     if ($bbag) {
3521         $self->ctx->{csv} = $U->fire_object_event(
3522             undef, "container.biblio_record_entry_bucket.csv",
3523             $bbag, $self->editor->requestor->home_ou,
3524             undef, {"item_search" => $item_search}
3525         );
3526     }
3527
3528     # Create a reasonable filename and set the content disposition to
3529     # provoke browser download dialogs.
3530     (my $filename = $bbag->id . $bbag->name) =~ s/[^a-z0-9_ -]//gi;
3531
3532     return $self->set_file_download_headers("$filename.csv");
3533 }
3534
3535 sub load_myopac_circ_history_export {
3536     my $self = shift;
3537     my $e = $self->editor;
3538     my $filename = $self->cgi->param('filename') || 'circ_history.csv';
3539
3540     my $circs = $self->fetch_user_circ_history(1);
3541
3542     $self->ctx->{csv}->{circs} = $circs;
3543     return $self->set_file_download_headers($filename, 'text/csv; encoding=UTF-8');
3544
3545 }
3546
3547 sub load_myopac_reservations {
3548     my $self = shift;
3549     my $e = $self->editor;
3550     my $ctx = $self->ctx;
3551
3552     my $upcoming = $U->simplereq("open-ils.booking", "open-ils.booking.reservations.upcoming_reservation_list_by_user",
3553         $e->authtoken, undef
3554     );
3555
3556     $ctx->{reservations} = $upcoming;
3557     return Apache2::Const::OK;
3558
3559 }
3560
3561 sub load_password_reset {
3562     my $self = shift;
3563     my $cgi = $self->cgi;
3564     my $ctx = $self->ctx;
3565     my $barcode = $cgi->param('barcode');
3566     my $username = $cgi->param('username');
3567     my $email = $cgi->param('email');
3568     my $pwd1 = $cgi->param('pwd1');
3569     my $pwd2 = $cgi->param('pwd2');
3570     my $uuid = $ctx->{page_args}->[0];
3571
3572     if ($uuid) {
3573
3574         $logger->info("patron password reset with uuid $uuid");
3575
3576         if ($pwd1 and $pwd2) {
3577
3578             if ($pwd1 eq $pwd2) {
3579
3580                 my $response = $U->simplereq(
3581                     'open-ils.actor',
3582                     'open-ils.actor.patron.password_reset.commit',
3583                     $uuid, $pwd1);
3584
3585                 $logger->info("patron password reset response " . Dumper($response));
3586
3587                 if ($U->event_code($response)) { # non-success event
3588
3589                     my $code = $response->{textcode};
3590
3591                     if ($code eq 'PATRON_NOT_AN_ACTIVE_PASSWORD_RESET_REQUEST') {
3592                         $ctx->{pwreset} = {style => 'error', status => 'NOT_ACTIVE'};
3593                     }
3594
3595                     if ($code eq 'PATRON_PASSWORD_WAS_NOT_STRONG') {
3596                         $ctx->{pwreset} = {style => 'error', status => 'NOT_STRONG'};
3597                     }
3598
3599                 } else { # success
3600
3601                     $ctx->{pwreset} = {style => 'success', status => 'SUCCESS'};
3602                 }
3603
3604             } else { # passwords not equal
3605
3606                 $ctx->{pwreset} = {style => 'error', status => 'NO_MATCH'};
3607             }
3608
3609         } else { # 2 password values needed
3610
3611             $ctx->{pwreset} = {status => 'TWO_PASSWORDS'};
3612         }
3613
3614     } elsif ($barcode or $username) {
3615
3616         my @params = $barcode ? ('barcode', $barcode) : ('username', $username);
3617         push(@params, $email) if $email;
3618
3619         $U->simplereq(
3620             'open-ils.actor',
3621             'open-ils.actor.patron.password_reset.request', @params);
3622
3623         $ctx->{pwreset} = {status => 'REQUEST_SUCCESS'};
3624     }
3625
3626     $logger->info("patron password reset resulted in " . Dumper($ctx->{pwreset}));
3627     return Apache2::Const::OK;
3628 }
3629
3630 1;