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