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