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