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