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