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