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