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