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