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