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