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