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