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