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