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