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