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