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