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