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