]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
Speed up hold editing by only fetching hold to edit
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Account.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
4 use OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
8 use OpenILS::Event;
9 use OpenSRF::Utils::JSON;
10 use Data::Dumper;
11 $Data::Dumper::Indent = 0;
12 use DateTime;
13 my $U = 'OpenILS::Application::AppUtils';
14
15 sub prepare_extended_user_info {
16     my $self = shift;
17     my @extra_flesh = @_;
18
19     $self->ctx->{user} = $self->editor->retrieve_actor_user([
20         $self->ctx->{user}->id,
21         {
22             flesh => 1,
23             flesh_fields => {
24                 au => [qw/card home_ou addresses ident_type billing_address/, @extra_flesh]
25                 # ...
26             }
27         }
28     ]) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
29
30     return;
31 }
32
33 # Given an event returned by a failed attempt to create a hold, do we have
34 # permission to override?  XXX Should the permission check be scoped to a
35 # given org_unit context?
36 sub test_could_override {
37     my ($self) = @_;
38     my $event = $self->ctx->{"hold_failed_event"};
39
40     return 0 unless $event;
41     return 1 if $self->editor->allowed($event . ".override");
42     return 1 if $event->{"fail_part"} and
43         $self->editor->allowed($event->{"fail_part"} . ".override");
44     return 0;
45 }
46
47 # Find out whether we care that local copies are available
48 sub local_avail_concern {
49     my ($self, $allowed, $hold_target, $hold_type, $pickup_lib) = @_;
50
51     my $would_block = $self->ctx->{get_org_setting}->
52         ($pickup_lib, "circ.holds.hold_has_copy_at.block");
53     my $would_alert = (
54         $self->ctx->{get_org_setting}->
55             ($pickup_lib, "circ.holds.hold_has_copy_at.alert") and
56                 not $self->cgi->param("override")
57     ) unless $would_block;
58
59     if ($allowed->{"success"} and ($would_block or $would_alert)) {
60         my $args = {
61             "hold_target" => $hold_target,
62             "hold_type" => $hold_type,
63             "org_unit" => $pickup_lib
64         };
65         my $local_avail = $U->simplereq(
66             "open-ils.circ",
67             "open-ils.circ.hold.has_copy_at", $self->editor->authtoken, $args
68         );
69         $logger->info(
70             "copy availability information for " . Dumper($args) .
71             " is " . Dumper($local_avail)
72         );
73         if (%$local_avail) { # if hash not empty
74             $self->ctx->{hold_copy_available} = $local_avail;
75             return ($would_block, $would_alert);
76         }
77     }
78
79     return (0, 0);
80 }
81
82 # context additions: 
83 #   user : au object, fleshed
84 sub load_myopac_prefs {
85     my $self = shift;
86     return $self->prepare_extended_user_info || Apache2::Const::OK;
87 }
88
89 sub load_myopac_prefs_notify {
90     my $self = shift;
91     my $e = $self->editor;
92
93     my $user_prefs = $self->fetch_optin_prefs;
94     $user_prefs = $self->update_optin_prefs($user_prefs)
95         if $self->cgi->request_method eq 'POST';
96
97     $self->ctx->{opt_in_settings} = $user_prefs; 
98
99     return Apache2::Const::OK;
100 }
101
102 sub fetch_optin_prefs {
103     my $self = shift;
104     my $e = $self->editor;
105
106     # fetch all of the opt-in settings the user has access to
107     # XXX: user's should in theory have options to opt-in to notices
108     # for remote locations, but that opens the door for a large
109     # set of generally un-used opt-ins.. needs discussion
110     my $opt_ins =  $U->simplereq(
111         'open-ils.actor',
112         'open-ils.actor.event_def.opt_in.settings.atomic',
113         $e->authtoken, $e->requestor->home_ou);
114
115     # fetch user setting values for each of the opt-in settings
116     my $user_set = $U->simplereq(
117         'open-ils.actor',
118         'open-ils.actor.patron.settings.retrieve',
119         $e->authtoken, 
120         $e->requestor->id, 
121         [map {$_->name} @$opt_ins]
122     );
123
124     return [map { {cust => $_, value => $user_set->{$_->name} } } @$opt_ins];
125 }
126
127 sub update_optin_prefs {
128     my $self = shift;
129     my $user_prefs = shift;
130     my $e = $self->editor;
131     my @settings = $self->cgi->param('setting');
132     my %newsets;
133
134     # apply now-true settings
135     for my $applied (@settings) {
136         # see if setting is already applied to this user
137         next if grep { $_->{cust}->name eq $applied and $_->{value} } @$user_prefs;
138         $newsets{$applied} = OpenSRF::Utils::JSON->true;
139     }
140
141     # remove now-false settings
142     for my $pref (grep { $_->{value} } @$user_prefs) {
143         $newsets{$pref->{cust}->name} = undef 
144             unless grep { $_ eq $pref->{cust}->name } @settings;
145     }
146
147     $U->simplereq(
148         'open-ils.actor',
149         'open-ils.actor.patron.settings.update',
150         $e->authtoken, $e->requestor->id, \%newsets);
151
152     # update the local prefs to match reality
153     for my $pref (@$user_prefs) {
154         $pref->{value} = $newsets{$pref->{cust}->name} 
155             if exists $newsets{$pref->{cust}->name};
156     }
157
158     return $user_prefs;
159 }
160
161 sub _load_user_with_prefs {
162     my $self = shift;
163     my $stat = $self->prepare_extended_user_info('settings');
164     return $stat if $stat; # not-OK
165
166     $self->ctx->{user_setting_map} = {
167         map { $_->name => OpenSRF::Utils::JSON->JSON2perl($_->value) } 
168             @{$self->ctx->{user}->settings}
169     };
170
171     return undef;
172 }
173
174 sub load_myopac_prefs_settings {
175     my $self = shift;
176
177     my $stat = $self->_load_user_with_prefs;
178     return $stat if $stat;
179
180     return Apache2::Const::OK
181         unless $self->cgi->request_method eq 'POST';
182
183     # some setting values from the form don't match the 
184     # required value/format for the db, so they have to be 
185     # individually translated.
186
187     my %settings;
188     my $set_map = $self->ctx->{user_setting_map};
189
190     my $key = 'opac.hits_per_page';
191     my $val = $self->cgi->param($key);
192     $settings{$key}= $val unless $$set_map{$key} eq $val;
193
194     my $now = DateTime->now->strftime('%F');
195     for $key (qw/history.circ.retention_start history.hold.retention_start/) {
196         $val = $self->cgi->param($key);
197         if($val and $val eq 'on') {
198             # Set the start time to 'now' unless a start time already exists for the user
199             $settings{$key} = $now unless $$set_map{$key};
200         } else {
201             # clear the start time if one previously existed for the user
202             $settings{$key} = undef if $$set_map{$key};
203         }
204     }
205     
206     # Send the modified settings off to be saved
207     $U->simplereq(
208         'open-ils.actor', 
209         'open-ils.actor.patron.settings.update',
210         $self->editor->authtoken, undef, \%settings);
211
212     # re-fetch user prefs 
213     $self->ctx->{updated_user_settings} = \%settings;
214     return $self->_load_user_with_prefs || Apache2::Const::OK;
215 }
216
217 sub fetch_user_holds {
218     my $self = shift;
219     my $hold_ids = shift;
220     my $ids_only = shift;
221     my $flesh = shift;
222     my $available = shift;
223     my $limit = shift;
224     my $offset = shift;
225
226     my $e = $self->editor;
227
228     if(!$hold_ids) {
229         my $circ = OpenSRF::AppSession->create('open-ils.circ');
230
231         $hold_ids = $circ->request(
232             'open-ils.circ.holds.id_list.retrieve.authoritative', 
233             $e->authtoken, 
234             $e->requestor->id
235         )->gather(1);
236         $circ->kill_me;
237     
238         $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
239     }
240
241
242     return $hold_ids if $ids_only or @$hold_ids == 0;
243
244     my $args = {
245         suppress_notices => 1,
246         suppress_transits => 1,
247         suppress_mvr => 1,
248         suppress_patron_details => 1,
249         include_bre => $flesh ? 1 : 0
250     };
251
252     # ----------------------------------------------------------------
253     # Collect holds in batches of $batch_size for faster retrieval
254
255     my $batch_size = 8;
256     my $batch_idx = 0;
257     my $mk_req_batch = sub {
258         my @ses;
259         my $top_idx = $batch_idx + $batch_size;
260         while($batch_idx < $top_idx) {
261             my $hold_id = $hold_ids->[$batch_idx++];
262             last unless $hold_id;
263             my $ses = OpenSRF::AppSession->create('open-ils.circ');
264             my $req = $ses->request(
265                 'open-ils.circ.hold.details.retrieve', 
266                 $e->authtoken, $hold_id, $args);
267             push(@ses, {ses => $ses, req => $req});
268         }
269         return @ses;
270     };
271
272     my $first = 1;
273     my(@collected, @holds, @ses);
274
275     while(1) {
276         @ses = $mk_req_batch->() if $first;
277         last if $first and not @ses;
278
279         if(@collected) {
280             # If desired by the caller, filter any holds that are not available.
281             if ($available) {
282                 @collected = grep { $_->{hold}->{status} == 4 } @collected;
283             }
284             while(my $blob = pop(@collected)) {
285                 $blob->{marc_xml} = XML::LibXML->new->parse_string($blob->{hold}->{bre}->marc) if $flesh;
286                 push(@holds, $blob);
287             }
288         }
289
290         for my $req_data (@ses) {
291             push(@collected, {hold => $req_data->{req}->gather(1)});
292             $req_data->{ses}->kill_me;
293         }
294
295         @ses = $mk_req_batch->();
296         last unless @collected or @ses;
297         $first = 0;
298     }
299
300     # put the holds back into the original server sort order
301     my @sorted;
302     for my $id (@$hold_ids) {
303         push @sorted, grep { $_->{hold}->{hold}->id == $id } @holds;
304     }
305
306     return \@sorted;
307 }
308
309 sub handle_hold_update {
310     my $self = shift;
311     my $action = shift;
312     my $hold_ids = shift;
313     my $e = $self->editor;
314     my $url;
315
316     my @hold_ids = ($hold_ids) ? @$hold_ids : $self->cgi->param('hold_id'); # for non-_all actions
317     @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
318
319     my $circ = OpenSRF::AppSession->create('open-ils.circ');
320
321     if($action =~ /cancel/) {
322
323         for my $hold_id (@hold_ids) {
324             my $resp = $circ->request(
325                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
326         }
327
328     } elsif ($action =~ /activate|suspend/) {
329         
330         my $vlist = [];
331         for my $hold_id (@hold_ids) {
332             my $vals = {id => $hold_id};
333
334             if($action =~ /activate/) {
335                 $vals->{frozen} = 'f';
336                 $vals->{thaw_date} = undef;
337
338             } elsif($action =~ /suspend/) {
339                 $vals->{frozen} = 't';
340                 # $vals->{thaw_date} = TODO;
341             }
342             push(@$vlist, $vals);
343         }
344
345         $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
346     } elsif ($action eq 'edit') {
347
348         my @vals = map {
349             my $val = {"id" => $_};
350             $val->{"frozen"} = $self->cgi->param("frozen");
351             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
352
353             for my $field (qw/expire_time thaw_date/) {
354                 # XXX TODO make this support other date formats, not just
355                 # MM/DD/YYYY.
356                 next unless $self->cgi->param($field) =~
357                     m:^(\d{2})/(\d{2})/(\d{4})$:;
358                 $val->{$field} = "$3-$1-$2";
359             }
360             $val;
361         } @hold_ids;
362
363         $circ->request(
364             'open-ils.circ.hold.update.batch.atomic',
365             $e->authtoken, undef, \@vals
366         )->gather(1);   # LFW XXX test for failure
367         $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
368     }
369
370     $circ->kill_me;
371     return defined($url) ? $self->generic_redirect($url) : undef;
372 }
373
374 sub load_myopac_holds {
375     my $self = shift;
376     my $e = $self->editor;
377     my $ctx = $self->ctx;
378     
379     my $limit = $self->cgi->param('limit') || 0;
380     my $offset = $self->cgi->param('offset') || 0;
381     my $action = $self->cgi->param('action') || '';
382     my $hold_id = $self->cgi->param('id');
383     my $available = int($self->cgi->param('available') || 0);
384
385     my $hold_handle_result;
386     $hold_handle_result = $self->handle_hold_update($action) if $action;
387
388     $ctx->{holds} = $self->fetch_user_holds($hold_id ? [$hold_id] : undef, 0, 1, $available, $limit, $offset);
389
390     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
391 }
392
393 sub load_place_hold {
394     my $self = shift;
395     my $ctx = $self->ctx;
396     my $gos = $ctx->{get_org_setting};
397     my $e = $self->editor;
398     my $cgi = $self->cgi;
399     $self->ctx->{page} = 'place_hold';
400
401     $ctx->{hold_target} = $cgi->param('hold_target');
402     $ctx->{hold_type} = $cgi->param('hold_type');
403
404     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
405
406     if (my $bc = $self->cgi->cookie("patron_barcode")) {
407         # passed in from staff client
408         $ctx->{patron_recipient} = $U->simplereq(
409             "open-ils.actor", "open-ils.actor.user.fleshed.retrieve_by_barcode",
410             $self->editor->authtoken, $bc
411         ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
412
413         $ctx->{default_pickup_lib} = $ctx->{patron_recipient}->home_ou;
414     }
415
416     my $request_lib = $e->requestor->ws_ou;
417
418     # XXX check for failure of the retrieve_* methods called below, and
419     # possibly replace all the if,elsif with a dispatch table (meh, elegance)
420
421     my $target_field;
422     if ($ctx->{hold_type} eq 'T') {
423         $target_field = "titleid";
424         $ctx->{record} = $e->retrieve_biblio_record_entry($ctx->{hold_target});
425     } elsif ($ctx->{hold_type} eq 'V') {
426         $target_field = "volume_id";
427         my $vol = $e->retrieve_asset_call_number([
428             $ctx->{hold_target}, {
429                 "flesh" => 1,
430                 "flesh_fields" => {"acn" => ["record"]}
431             }
432         ]);
433         $ctx->{record} = $vol->record;
434     } elsif ($ctx->{hold_type} eq 'C') {
435         $target_field = "copy_id";
436         my $copy = $e->retrieve_asset_copy([
437             $ctx->{hold_target}, {
438                 "flesh" => 2,
439                 "flesh_fields" => {
440                     "acn" => ["record"],
441                     "acp" => ["call_number"]
442                 }
443             }
444         ]);
445         $ctx->{record} = $copy->call_number->record;
446     } elsif ($ctx->{hold_type} eq 'I') {
447         $target_field = "issuanceid";
448         my $iss = $e->retrieve_serial_issuance([
449             $ctx->{hold_target}, {
450                 "flesh" => 2,
451                 "flesh_fields" => {
452                     "siss" => ["subscription"], "ssub" => ["record_entry"]
453                 }
454             }
455         ]);
456         $ctx->{record} = $iss->subscription->record_entry;
457     }
458     # ...
459
460     $ctx->{marc_xml} = XML::LibXML->new->parse_string($ctx->{record}->marc);
461
462     if (my $pickup_lib = $cgi->param('pickup_lib')) {
463         my $requestor = $e->requestor->id;
464         my $usr; 
465
466         if ((not $ctx->{"is_staff"}) or
467             ($cgi->param("hold_usr_is_requestor"))) {
468             $usr = $requestor;
469         } else {
470             my $actor = create OpenSRF::AppSession("open-ils.actor");
471             $usr = $actor->request(
472                 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
473                 $e->authtoken, $cgi->param("hold_usr")
474             )->gather(1);
475
476             if (defined $U->event_code($usr)) {
477                 $ctx->{hold_failed} = 1;
478                 $ctx->{hold_failed_event} = $usr;
479             }
480             $actor->kill_me;
481         }
482
483         my $args = {
484             patronid => $usr,
485             $target_field => $ctx->{"hold_target"},
486             pickup_lib => $pickup_lib,
487             hold_type => $ctx->{"hold_type"},
488             depth => 0, # XXX
489         };
490
491         my $allowed = $U->simplereq(
492             'open-ils.circ',
493             'open-ils.circ.title_hold.is_possible',
494             $e->authtoken, $args
495         );
496
497         $logger->info('hold permit result ' . OpenSRF::Utils::JSON->perl2JSON($allowed));
498
499         my ($local_block, $local_alert) = $self->local_avail_concern(
500             $allowed, $args->{$target_field}, $args->{hold_type}, $pickup_lib
501         );
502
503         # Give the original CGI params back to the user in case they
504         # want to try to override something.
505         $ctx->{orig_params} = $cgi->Vars;
506
507         if ($local_block) {
508             $ctx->{hold_failed} = 1;
509             $ctx->{hold_local_block} = 1;
510         } elsif ($local_alert) {
511             $ctx->{hold_failed} = 1;
512             $ctx->{hold_local_alert} = 1;
513         } elsif ($allowed->{success}) {
514             my $hold = Fieldmapper::action::hold_request->new;
515
516             $hold->pickup_lib($pickup_lib);
517             $hold->requestor($requestor);
518             $hold->usr($usr);
519             $hold->target($ctx->{hold_target});
520             $hold->hold_type($ctx->{hold_type});
521             # frozen, expired, etc..
522
523             my $method =  "open-ils.circ.holds.create";
524             $method .= ".override" if $cgi->param("override");
525
526             my $stat = $U->simplereq(
527                 "open-ils.circ", $method, $e->authtoken, $hold
528             );
529
530             # The following did not cover all the possible return values of
531             # open-ils.circ.holds.create
532             #if($stat and $stat > 0) {
533             if ($stat and (not ref $stat) and $stat > 0) {
534                 # if successful, return the user to the requesting page
535                 $self->apache->log->info(
536                     "Redirecting back to " . $cgi->param('redirect_to')
537                 );
538
539                 # We also clear the patron_barcode (from the staff client)
540                 # cookie at this point (otherwise it haunts the staff user
541                 # later). XXX todo make sure this is best; also see that
542                 # template when staff mode calls xulG.opac_hold_placed()
543                 return $self->generic_redirect(
544                     undef,
545                     $self->cgi->cookie(
546                         -name => "patron_barcode",
547                         -path => "/",
548                         -secure => 1,
549                         -value => "",
550                         -expires => "-1h"
551                     )
552                 );
553
554             } else {
555                 $ctx->{hold_failed} = 1;
556
557                 delete $ctx->{orig_params}{submit};
558
559                 if (ref $stat eq 'ARRAY') {
560                     $ctx->{hold_failed_event} = shift @$stat;
561                 } elsif (defined $U->event_code($stat)) {
562                     $ctx->{hold_failed_event} = $stat;
563                 } else {
564                     $self->apache->log->info(
565                         "attempt to create hold returned $stat"
566                     );
567                 }
568
569                 $ctx->{could_override} = $self->test_could_override;
570             }
571         } else { # hold *check* failed
572             $ctx->{hold_failed} = 1; # XXX process the events, etc
573             $ctx->{hold_failed_event} = $allowed->{last_event};
574         }
575
576         # hold permit failed
577     }
578
579     return Apache2::Const::OK;
580 }
581
582
583 sub fetch_user_circs {
584     my $self = shift;
585     my $flesh = shift; # flesh bib data, etc.
586     my $circ_ids = shift;
587     my $limit = shift;
588     my $offset = shift;
589
590     my $e = $self->editor;
591
592     my @circ_ids;
593
594     if($circ_ids) {
595         @circ_ids = @$circ_ids;
596
597     } else {
598
599         my $circ_data = $U->simplereq(
600             'open-ils.actor', 
601             'open-ils.actor.user.checked_out',
602             $e->authtoken, 
603             $e->requestor->id
604         );
605
606         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
607
608         if($limit or $offset) {
609             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
610         }
611     }
612
613     return [] unless @circ_ids;
614
615     my $qflesh = {
616         flesh => 3,
617         flesh_fields => {
618             circ => ['target_copy'],
619             acp => ['call_number'],
620             acn => ['record']
621         }
622     };
623
624     $e->xact_begin;
625     my $circs = $e->search_action_circulation(
626         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
627
628     my @circs;
629     for my $circ (@$circs) {
630         push(@circs, {
631             circ => $circ, 
632             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
633                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
634                 undef  # pre-cat copy, use the dummy title/author instead
635         });
636     }
637     $e->xact_rollback;
638
639     # make sure the final list is in the correct order
640     my @sorted_circs;
641     for my $id (@circ_ids) {
642         push(
643             @sorted_circs,
644             (grep { $_->{circ}->id == $id } @circs)
645         );
646     }
647
648     return \@sorted_circs;
649 }
650
651
652 sub handle_circ_renew {
653     my $self = shift;
654     my $action = shift;
655     my $ctx = $self->ctx;
656
657     my @renew_ids = $self->cgi->param('circ');
658
659     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
660
661     # TODO: fire off renewal calls in batches to speed things up
662     my @responses;
663     for my $circ (@$circs) {
664
665         my $evt = $U->simplereq(
666             'open-ils.circ', 
667             'open-ils.circ.renew',
668             $self->editor->authtoken,
669             {
670                 patron_id => $self->editor->requestor->id,
671                 copy_id => $circ->{circ}->target_copy,
672                 opac_renewal => 1
673             }
674         );
675
676         # TODO return these, then insert them into the circ data 
677         # blob that is shoved into the template for each circ
678         # so the template won't have to match them
679         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
680     }
681
682     return @responses;
683 }
684
685
686 sub load_myopac_circs {
687     my $self = shift;
688     my $e = $self->editor;
689     my $ctx = $self->ctx;
690
691     $ctx->{circs} = [];
692     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
693     my $offset = $self->cgi->param('offset') || 0;
694     my $action = $self->cgi->param('action') || '';
695
696     # perform the renewal first if necessary
697     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
698
699     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
700
701     my $success_renewals = 0;
702     my $failed_renewals = 0;
703     for my $data (@{$ctx->{circs}}) {
704         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
705
706         if($resp) {
707             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
708             $data->{renewal_response} = $evt;
709             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
710             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
711         }
712     }
713
714     $ctx->{success_renewals} = $success_renewals;
715     $ctx->{failed_renewals} = $failed_renewals;
716
717     return Apache2::Const::OK;
718 }
719
720 sub load_myopac_circ_history {
721     my $self = shift;
722     my $e = $self->editor;
723     my $ctx = $self->ctx;
724     my $limit = $self->cgi->param('limit') || 15;
725     my $offset = $self->cgi->param('offset') || 0;
726
727     $ctx->{circ_history_limit} = $limit;
728     $ctx->{circ_history_offset} = $offset;
729
730     my $circs = $e->json_query({
731         from => ['action.usr_visible_circs', $e->requestor->id],
732         #limit => $limit || 25,
733         #offset => $offset || 0,
734     });
735
736     # XXX: order-by in the json_query above appears to do nothing, so in-query 
737     # paging is not reallly an option.  do the sorting/paging here
738
739     # sort newest to oldest
740     $circs = [ sort { $b->{xact_start} cmp $a->{xact_start} } @$circs ];
741     my @ids = map { $_->{id} } @$circs;
742
743     # find the selected page and trim cruft
744     @ids = @ids[$offset..($offset + $limit - 1)] if $limit;
745     @ids = grep { defined $_ } @ids;
746
747     $ctx->{circs} = $self->fetch_user_circs(1, \@ids);
748     #$ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circs], $limit, $offset);
749
750     return Apache2::Const::OK;
751 }
752
753 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
754 sub load_myopac_hold_history {
755     my $self = shift;
756     my $e = $self->editor;
757     my $ctx = $self->ctx;
758     my $limit = $self->cgi->param('limit') || 15;
759     my $offset = $self->cgi->param('offset') || 0;
760     $ctx->{hold_history_limit} = $limit;
761     $ctx->{hold_history_offset} = $offset;
762
763
764     my $holds = $e->json_query({
765         from => ['action.usr_visible_holds', $e->requestor->id],
766         limit => $limit || 25,
767         offset => $offset || 0
768     });
769
770     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$holds], 0, 1, 0, $limit, $offset);
771
772     return Apache2::Const::OK;
773 }
774
775 sub load_myopac_payment_form {
776     my $self = shift;
777     my $r;
778
779     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
780     $r = $self->prepare_extended_user_info and return $r;
781
782     return Apache2::Const::OK;
783 }
784
785 # TODO: add other filter options as params/configs/etc.
786 sub load_myopac_payments {
787     my $self = shift;
788     my $limit = $self->cgi->param('limit') || 20;
789     my $offset = $self->cgi->param('offset') || 0;
790     my $e = $self->editor;
791
792     $self->ctx->{payment_history_limit} = $limit;
793     $self->ctx->{payment_history_offset} = $offset;
794
795     my $args = {};
796     $args->{limit} = $limit if $limit;
797     $args->{offset} = $offset if $offset;
798
799     if (my $max_age = $self->ctx->{get_org_setting}->(
800         $e->requestor->home_ou, "opac.payment_history_age_limit"
801     )) {
802         my $min_ts = DateTime->now(
803             "time_zone" => DateTime::TimeZone->new("name" => "local"),
804         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
805         
806         $logger->info("XXX min_ts: $min_ts");
807         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
808     }
809
810     $self->ctx->{payments} = $U->simplereq(
811         'open-ils.actor',
812         'open-ils.actor.user.payments.retrieve.atomic',
813         $e->authtoken, $e->requestor->id, $args);
814
815     return Apache2::Const::OK;
816 }
817
818 sub load_myopac_pay {
819     my $self = shift;
820     my $r;
821
822     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and
823         return $r;
824
825     # balance_owed is computed specifically from the fines we're trying
826     # to pay in this case.
827     if ($self->ctx->{fines}->{balance_owed} <= 0) {
828         $self->apache->log->info(
829             sprintf("Can't pay non-positive balance. xacts selected: (%s)",
830                 join(", ", map(int, $self->cgi->param("xact"), $self->cgi->param('xact_misc'))))
831         );
832         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
833     }
834
835     my $cc_args = {"where_process" => 1};
836
837     $cc_args->{$_} = $self->cgi->param($_) for (qw/
838         number cvv2 expire_year expire_month billing_first
839         billing_last billing_address billing_city billing_state
840         billing_zip
841     /);
842
843     my $args = {
844         "cc_args" => $cc_args,
845         "userid" => $self->ctx->{user}->id,
846         "payment_type" => "credit_card_payment",
847         "payments" => $self->prepare_fines_for_payment   # should be safe after self->prepare_fines
848     };
849
850     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
851         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
852     );
853
854     $self->ctx->{"payment_response"} = $resp;
855
856     unless ($resp->{"textcode"}) {
857         $self->ctx->{printable_receipt} = $U->simplereq(
858            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
859            $self->editor->authtoken, $resp->{payments}
860         );
861     }
862
863     return Apache2::Const::OK;
864 }
865
866 sub load_myopac_receipt_print {
867     my $self = shift;
868
869     $self->ctx->{printable_receipt} = $U->simplereq(
870        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
871        $self->editor->authtoken, [$self->cgi->param("payment")]
872     );
873
874     return Apache2::Const::OK;
875 }
876
877 sub load_myopac_receipt_email {
878     my $self = shift;
879
880     # The following ML method doesn't actually check whether the user in
881     # question has an email address, so we do.
882     if ($self->ctx->{user}->email) {
883         $self->ctx->{email_receipt_result} = $U->simplereq(
884            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
885            $self->editor->authtoken, [$self->cgi->param("payment")]
886         );
887     } else {
888         $self->ctx->{email_receipt_result} =
889             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
890     }
891
892     return Apache2::Const::OK;
893 }
894
895 sub prepare_fines {
896     my ($self, $limit, $offset, $id_list) = @_;
897
898     # XXX TODO: check for failure after various network calls
899
900     # It may be unclear, but this result structure lumps circulation and
901     # reservation fines together, and keeps grocery fines separate.
902     $self->ctx->{"fines"} = {
903         "circulation" => [],
904         "grocery" => [],
905         "total_paid" => 0,
906         "total_owed" => 0,
907         "balance_owed" => 0
908     };
909
910     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
911
912     # TODO: This should really be a ML call, but the existing calls 
913     # return an excessive amount of data and don't offer streaming
914
915     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
916
917     my $req = $cstore->request(
918         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
919         {
920             usr => $self->editor->requestor->id,
921             balance_owed => {'!=' => 0},
922             ($id_list && @$id_list ? ("id" => $id_list) : ()),
923         },
924         {
925             flesh => 4,
926             flesh_fields => {
927                 mobts => [qw/grocery circulation reservation/],
928                 bresv => ['target_resource_type'],
929                 brt => ['record'],
930                 mg => ['billings'],
931                 mb => ['btype'],
932                 circ => ['target_copy'],
933                 acp => ['call_number'],
934                 acn => ['record']
935             },
936             order_by => { mobts => 'xact_start' },
937             %paging
938         }
939     );
940
941     my @total_keys = qw/total_paid total_owed balance_owed/;
942     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
943
944     while(my $resp = $req->recv) {
945         my $mobts = $resp->content;
946         my $circ = $mobts->circulation;
947
948         my $last_billing;
949         if($mobts->grocery) {
950             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
951             $last_billing = pop(@billings);
952         }
953
954         # XXX TODO confirm that the following, and the later division by 100.0
955         # to get a floating point representation once again, is sufficiently
956         # "money-safe" math.
957         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
958
959         my $marc_xml = undef;
960         if ($mobts->xact_type eq 'reservation' and
961             $mobts->reservation->target_resource_type->record) {
962             $marc_xml = XML::LibXML->new->parse_string(
963                 $mobts->reservation->target_resource_type->record->marc
964             );
965         } elsif ($mobts->xact_type eq 'circulation' and
966             $circ->target_copy->call_number->id != -1) {
967             $marc_xml = XML::LibXML->new->parse_string(
968                 $circ->target_copy->call_number->record->marc
969             );
970         }
971
972         push(
973             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
974             {
975                 xact => $mobts,
976                 last_grocery_billing => $last_billing,
977                 marc_xml => $marc_xml
978             } 
979         );
980     }
981
982     $cstore->kill_me;
983
984     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
985     return;
986 }
987
988 sub prepare_fines_for_payment {
989     # This assumes $self->prepare_fines has already been run
990     my ($self) = @_;
991
992     my @results = ();
993     if ($self->ctx->{fines}) {
994         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
995             @{$self->ctx->{fines}->{circulation}},
996             @{$self->ctx->{fines}->{grocery}}
997         );
998     }
999
1000     return \@results;
1001 }
1002
1003 sub load_myopac_main {
1004     my $self = shift;
1005     my $limit = $self->cgi->param('limit') || 0;
1006     my $offset = $self->cgi->param('offset') || 0;
1007
1008     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1009 }
1010
1011 sub load_myopac_update_email {
1012     my $self = shift;
1013     my $e = $self->editor;
1014     my $ctx = $self->ctx;
1015     my $email = $self->cgi->param('email') || '';
1016
1017     # needed for most up-to-date email address
1018     if (my $r = $self->prepare_extended_user_info) { return $r };
1019
1020     return Apache2::Const::OK 
1021         unless $self->cgi->request_method eq 'POST';
1022
1023     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1024         $ctx->{invalid_email} = $email;
1025         return Apache2::Const::OK;
1026     }
1027
1028     my $stat = $U->simplereq(
1029         'open-ils.actor', 
1030         'open-ils.actor.user.email.update', 
1031         $e->authtoken, $email);
1032
1033     unless ($self->cgi->param("redirect_to")) {
1034         my $url = $self->apache->unparsed_uri;
1035         $url =~ s/update_email/prefs/;
1036
1037         return $self->generic_redirect($url);
1038     }
1039
1040     return $self->generic_redirect;
1041 }
1042
1043 sub load_myopac_update_username {
1044     my $self = shift;
1045     my $e = $self->editor;
1046     my $ctx = $self->ctx;
1047     my $username = $self->cgi->param('username') || '';
1048
1049     return Apache2::Const::OK 
1050         unless $self->cgi->request_method eq 'POST';
1051
1052     unless($username and $username !~ /\s/) { # any other username restrictions?
1053         $ctx->{invalid_username} = $username;
1054         return Apache2::Const::OK;
1055     }
1056
1057     if($username ne $e->requestor->usrname) {
1058
1059         my $evt = $U->simplereq(
1060             'open-ils.actor', 
1061             'open-ils.actor.user.username.update', 
1062             $e->authtoken, $username);
1063
1064         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1065             $ctx->{username_exists} = $username;
1066             return Apache2::Const::OK;
1067         }
1068     }
1069
1070     my $url = $self->apache->unparsed_uri;
1071     $url =~ s/update_username/prefs/;
1072
1073     return $self->generic_redirect($url);
1074 }
1075
1076 sub load_myopac_update_password {
1077     my $self = shift;
1078     my $e = $self->editor;
1079     my $ctx = $self->ctx;
1080
1081     return Apache2::Const::OK 
1082         unless $self->cgi->request_method eq 'POST';
1083
1084     my $current_pw = $self->cgi->param('current_pw') || '';
1085     my $new_pw = $self->cgi->param('new_pw') || '';
1086     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1087
1088     unless($new_pw eq $new_pw2) {
1089         $ctx->{password_nomatch} = 1;
1090         return Apache2::Const::OK;
1091     }
1092
1093     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1094
1095     if($pw_regex and $new_pw !~ /$pw_regex/) {
1096         $ctx->{password_invalid} = 1;
1097         return Apache2::Const::OK;
1098     }
1099
1100     my $evt = $U->simplereq(
1101         'open-ils.actor', 
1102         'open-ils.actor.user.password.update', 
1103         $e->authtoken, $new_pw, $current_pw);
1104
1105
1106     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1107         $ctx->{password_incorrect} = 1;
1108         return Apache2::Const::OK;
1109     }
1110
1111     my $url = $self->apache->unparsed_uri;
1112     $url =~ s/update_password/prefs/;
1113
1114     return $self->generic_redirect($url);
1115 }
1116
1117 sub load_myopac_bookbags {
1118     my $self = shift;
1119     my $e = $self->editor;
1120     my $ctx = $self->ctx;
1121
1122     $e->xact_begin; # replication...
1123
1124     my $rv = $self->load_mylist;
1125     unless($rv eq Apache2::Const::OK) {
1126         $e->rollback;
1127         return $rv;
1128     }
1129
1130     my $args = {
1131         order_by => {cbreb => 'name'},
1132         limit => $self->cgi->param('limit') || 10,
1133         offset => $self->cgi->param('offset') || 0
1134     };
1135
1136     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket([
1137         {owner => $self->editor->requestor->id, btype => 'bookbag'},
1138         # XXX what to do about the possibility of really large bookbags here?
1139         {"flesh" => 1, "flesh_fields" => {"cbreb" => ["items"]}, %$args}
1140     ]);
1141
1142     if(!$ctx->{bookbags}) {
1143         $e->rollback;
1144         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1145     }
1146     
1147     # get unique record IDs
1148     my %rec_ids = ();
1149     foreach my $bbag (@{$ctx->{bookbags}}) {
1150         foreach my $rec_id (
1151             map { $_->target_biblio_record_entry } @{$bbag->items}
1152         ) {
1153             $rec_ids{$rec_id} = 1;
1154         }
1155     }
1156
1157     $ctx->{bookbags_marc_xml} = $self->fetch_marc_xml_by_id([keys %rec_ids]);
1158
1159     $e->rollback;
1160     return Apache2::Const::OK;
1161 }
1162
1163
1164 # actions are create, delete, show, hide, rename, add_rec, delete_item
1165 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1166 sub load_myopac_bookbag_update {
1167     my ($self, $action, $list_id) = @_;
1168     my $e = $self->editor;
1169     my $cgi = $self->cgi;
1170
1171     $action ||= $cgi->param('action');
1172     $list_id ||= $cgi->param('list');
1173
1174     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1175     my @del_item = $cgi->param('del_item');
1176     my $shared = $cgi->param('shared');
1177     my $name = $cgi->param('name');
1178     my $success = 0;
1179     my $list;
1180
1181     if($action eq 'create') {
1182         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1183         $list->name($name);
1184         $list->owner($e->requestor->id);
1185         $list->btype('bookbag');
1186         $list->pub($shared ? 't' : 'f');
1187         $success = $U->simplereq('open-ils.actor', 
1188             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1189
1190     } else {
1191
1192         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1193
1194         return Apache2::Const::HTTP_BAD_REQUEST unless 
1195             $list and $list->owner == $e->requestor->id;
1196     }
1197
1198     if($action eq 'delete') {
1199         $success = $U->simplereq('open-ils.actor', 
1200             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1201
1202     } elsif($action eq 'show') {
1203         unless($U->is_true($list->pub)) {
1204             $list->pub('t');
1205             $success = $U->simplereq('open-ils.actor', 
1206                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1207         }
1208
1209     } elsif($action eq 'hide') {
1210         if($U->is_true($list->pub)) {
1211             $list->pub('f');
1212             $success = $U->simplereq('open-ils.actor', 
1213                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1214         }
1215
1216     } elsif($action eq 'rename') {
1217         if($name) {
1218             $list->name($name);
1219             $success = $U->simplereq('open-ils.actor', 
1220                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1221         }
1222
1223     } elsif($action eq 'add_rec') {
1224         foreach my $add_rec (@add_rec) {
1225             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1226             $item->bucket($list_id);
1227             $item->target_biblio_record_entry($add_rec);
1228             $success = $U->simplereq('open-ils.actor', 
1229                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1230             last unless $success;
1231         }
1232
1233     } elsif($action eq 'del_item') {
1234         foreach (@del_item) {
1235             $success = $U->simplereq(
1236                 'open-ils.actor',
1237                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1238             );
1239             last unless $success;
1240         }
1241     }
1242
1243     return $self->generic_redirect if $success;
1244
1245     $self->ctx->{bucket_action} = $action;
1246     $self->ctx->{bucket_action_failed} = 1;
1247     return Apache2::Const::OK;
1248 }
1249
1250 1