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