]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Account.pm
Repaired seed data T-pac merge conflict
[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 $e = $self->editor;
313     my $url;
314
315     my @hold_ids = $self->cgi->param('hold_id'); # for non-_all actions
316     @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
317
318     my $circ = OpenSRF::AppSession->create('open-ils.circ');
319
320     if($action =~ /cancel/) {
321
322         for my $hold_id (@hold_ids) {
323             my $resp = $circ->request(
324                 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
325         }
326
327     } elsif ($action =~ /activate|suspend/) {
328         
329         my $vlist = [];
330         for my $hold_id (@hold_ids) {
331             my $vals = {id => $hold_id};
332
333             if($action =~ /activate/) {
334                 $vals->{frozen} = 'f';
335                 $vals->{thaw_date} = undef;
336
337             } elsif($action =~ /suspend/) {
338                 $vals->{frozen} = 't';
339                 # $vals->{thaw_date} = TODO;
340             }
341             push(@$vlist, $vals);
342         }
343
344         $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
345     } elsif ($action eq 'edit') {
346
347         my @vals = map {
348             my $val = {"id" => $_};
349             $val->{"frozen"} = $self->cgi->param("frozen");
350             $val->{"pickup_lib"} = $self->cgi->param("pickup_lib");
351
352             for my $field (qw/expire_time thaw_date/) {
353                 # XXX TODO make this support other date formats, not just
354                 # MM/DD/YYYY.
355                 next unless $self->cgi->param($field) =~
356                     m:^(\d{2})/(\d{2})/(\d{4})$:;
357                 $val->{$field} = "$3-$1-$2";
358             }
359             $val;
360         } @hold_ids;
361
362         $circ->request(
363             'open-ils.circ.hold.update.batch.atomic',
364             $e->authtoken, undef, \@vals
365         )->gather(1);   # LFW XXX test for failure
366         $url = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . '/myopac/holds';
367     }
368
369     $circ->kill_me;
370     return defined($url) ? $self->generic_redirect($url) : undef;
371 }
372
373 sub load_myopac_holds {
374     my $self = shift;
375     my $e = $self->editor;
376     my $ctx = $self->ctx;
377     
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 $available = int($self->cgi->param('available') || 0);
383
384     my $hold_handle_result;
385     $hold_handle_result = $self->handle_hold_update($action) if $action;
386
387     $ctx->{holds} = $self->fetch_user_holds(undef, 0, 1, $available, $limit, $offset);
388
389     return defined($hold_handle_result) ? $hold_handle_result : Apache2::Const::OK;
390 }
391
392 sub load_place_hold {
393     my $self = shift;
394     my $ctx = $self->ctx;
395     my $gos = $ctx->{get_org_setting};
396     my $e = $self->editor;
397     my $cgi = $self->cgi;
398     $self->ctx->{page} = 'place_hold';
399
400     $ctx->{hold_target} = $cgi->param('hold_target');
401     $ctx->{hold_type} = $cgi->param('hold_type');
402
403     $ctx->{default_pickup_lib} = $e->requestor->home_ou; # unless changed below
404
405     if (my $bc = $self->cgi->cookie("patron_barcode")) {
406         # passed in from staff client
407         $ctx->{patron_recipient} = $U->simplereq(
408             "open-ils.actor", "open-ils.actor.user.fleshed.retrieve_by_barcode",
409             $self->editor->authtoken, $bc
410         ) or return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
411
412         $ctx->{default_pickup_lib} = $ctx->{patron_recipient}->home_ou;
413     }
414
415     my $request_lib = $e->requestor->ws_ou;
416
417     # XXX check for failure of the retrieve_* methods called below, and
418     # possibly replace all the if,elsif with a dispatch table (meh, elegance)
419
420     my $target_field;
421     if ($ctx->{hold_type} eq 'T') {
422         $target_field = "titleid";
423         $ctx->{record} = $e->retrieve_biblio_record_entry($ctx->{hold_target});
424     } elsif ($ctx->{hold_type} eq 'V') {
425         $target_field = "volume_id";
426         my $vol = $e->retrieve_asset_call_number([
427             $ctx->{hold_target}, {
428                 "flesh" => 1,
429                 "flesh_fields" => {"acn" => ["record"]}
430             }
431         ]);
432         $ctx->{record} = $vol->record;
433     } elsif ($ctx->{hold_type} eq 'C') {
434         $target_field = "copy_id";
435         my $copy = $e->retrieve_asset_copy([
436             $ctx->{hold_target}, {
437                 "flesh" => 2,
438                 "flesh_fields" => {
439                     "acn" => ["record"],
440                     "acp" => ["call_number"]
441                 }
442             }
443         ]);
444         $ctx->{record} = $copy->call_number->record;
445     } elsif ($ctx->{hold_type} eq 'I') {
446         $target_field = "issuanceid";
447         my $iss = $e->retrieve_serial_issuance([
448             $ctx->{hold_target}, {
449                 "flesh" => 2,
450                 "flesh_fields" => {
451                     "siss" => ["subscription"], "ssub" => ["record_entry"]
452                 }
453             }
454         ]);
455         $ctx->{record} = $iss->subscription->record_entry;
456     }
457     # ...
458
459     $ctx->{marc_xml} = XML::LibXML->new->parse_string($ctx->{record}->marc);
460
461     if (my $pickup_lib = $cgi->param('pickup_lib')) {
462         my $requestor = $e->requestor->id;
463         my $usr; 
464
465         if ((not $ctx->{"is_staff"}) or
466             ($cgi->param("hold_usr_is_requestor"))) {
467             $usr = $requestor;
468         } else {
469             my $actor = create OpenSRF::AppSession("open-ils.actor");
470             $usr = $actor->request(
471                 "open-ils.actor.user.retrieve_id_by_barcode_or_username",
472                 $e->authtoken, $cgi->param("hold_usr")
473             )->gather(1);
474
475             if (defined $U->event_code($usr)) {
476                 $ctx->{hold_failed} = 1;
477                 $ctx->{hold_failed_event} = $usr;
478             }
479             $actor->kill_me;
480         }
481
482         my $args = {
483             patronid => $usr,
484             $target_field => $ctx->{"hold_target"},
485             pickup_lib => $pickup_lib,
486             hold_type => $ctx->{"hold_type"},
487             depth => 0, # XXX
488         };
489
490         my $allowed = $U->simplereq(
491             'open-ils.circ',
492             'open-ils.circ.title_hold.is_possible',
493             $e->authtoken, $args
494         );
495
496         $logger->info('hold permit result ' . OpenSRF::Utils::JSON->perl2JSON($allowed));
497
498         my ($local_block, $local_alert) = $self->local_avail_concern(
499             $allowed, $args->{$target_field}, $args->{hold_type}, $pickup_lib
500         );
501
502         # Give the original CGI params back to the user in case they
503         # want to try to override something.
504         $ctx->{orig_params} = $cgi->Vars;
505
506         if ($local_block) {
507             $ctx->{hold_failed} = 1;
508             $ctx->{hold_local_block} = 1;
509         } elsif ($local_alert) {
510             $ctx->{hold_failed} = 1;
511             $ctx->{hold_local_alert} = 1;
512         } elsif ($allowed->{success}) {
513             my $hold = Fieldmapper::action::hold_request->new;
514
515             $hold->pickup_lib($pickup_lib);
516             $hold->requestor($requestor);
517             $hold->usr($usr);
518             $hold->target($ctx->{hold_target});
519             $hold->hold_type($ctx->{hold_type});
520             # frozen, expired, etc..
521
522             my $method =  "open-ils.circ.holds.create";
523             $method .= ".override" if $cgi->param("override");
524
525             my $stat = $U->simplereq(
526                 "open-ils.circ", $method, $e->authtoken, $hold
527             );
528
529             # The following did not cover all the possible return values of
530             # open-ils.circ.holds.create
531             #if($stat and $stat > 0) {
532             if ($stat and (not ref $stat) and $stat > 0) {
533                 # if successful, return the user to the requesting page
534                 $self->apache->log->info(
535                     "Redirecting back to " . $cgi->param('redirect_to')
536                 );
537
538                 # We also clear the patron_barcode (from the staff client)
539                 # cookie at this point (otherwise it haunts the staff user
540                 # later). XXX todo make sure this is best; also see that
541                 # template when staff mode calls xulG.opac_hold_placed()
542                 return $self->generic_redirect(
543                     undef,
544                     $self->cgi->cookie(
545                         -name => "patron_barcode",
546                         -path => "/",
547                         -secure => 1,
548                         -value => "",
549                         -expires => "-1h"
550                     )
551                 );
552
553             } else {
554                 $ctx->{hold_failed} = 1;
555
556                 delete $ctx->{orig_params}{submit};
557
558                 if (ref $stat eq 'ARRAY') {
559                     $ctx->{hold_failed_event} = shift @$stat;
560                 } elsif (defined $U->event_code($stat)) {
561                     $ctx->{hold_failed_event} = $stat;
562                 } else {
563                     $self->apache->log->info(
564                         "attempt to create hold returned $stat"
565                     );
566                 }
567
568                 $ctx->{could_override} = $self->test_could_override;
569             }
570         } else { # hold *check* failed
571             $ctx->{hold_failed} = 1; # XXX process the events, etc
572             $ctx->{hold_failed_event} = $allowed->{last_event};
573         }
574
575         # hold permit failed
576     }
577
578     return Apache2::Const::OK;
579 }
580
581
582 sub fetch_user_circs {
583     my $self = shift;
584     my $flesh = shift; # flesh bib data, etc.
585     my $circ_ids = shift;
586     my $limit = shift;
587     my $offset = shift;
588
589     my $e = $self->editor;
590
591     my @circ_ids;
592
593     if($circ_ids) {
594         @circ_ids = @$circ_ids;
595
596     } else {
597
598         my $circ_data = $U->simplereq(
599             'open-ils.actor', 
600             'open-ils.actor.user.checked_out',
601             $e->authtoken, 
602             $e->requestor->id
603         );
604
605         @circ_ids =  ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
606
607         if($limit or $offset) {
608             @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
609         }
610     }
611
612     return [] unless @circ_ids;
613
614     my $qflesh = {
615         flesh => 3,
616         flesh_fields => {
617             circ => ['target_copy'],
618             acp => ['call_number'],
619             acn => ['record']
620         }
621     };
622
623     $e->xact_begin;
624     my $circs = $e->search_action_circulation(
625         [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
626
627     my @circs;
628     for my $circ (@$circs) {
629         push(@circs, {
630             circ => $circ, 
631             marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ? 
632                 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) : 
633                 undef  # pre-cat copy, use the dummy title/author instead
634         });
635     }
636     $e->xact_rollback;
637
638     # make sure the final list is in the correct order
639     my @sorted_circs;
640     for my $id (@circ_ids) {
641         push(
642             @sorted_circs,
643             (grep { $_->{circ}->id == $id } @circs)
644         );
645     }
646
647     return \@sorted_circs;
648 }
649
650
651 sub handle_circ_renew {
652     my $self = shift;
653     my $action = shift;
654     my $ctx = $self->ctx;
655
656     my @renew_ids = $self->cgi->param('circ');
657
658     my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
659
660     # TODO: fire off renewal calls in batches to speed things up
661     my @responses;
662     for my $circ (@$circs) {
663
664         my $evt = $U->simplereq(
665             'open-ils.circ', 
666             'open-ils.circ.renew',
667             $self->editor->authtoken,
668             {
669                 patron_id => $self->editor->requestor->id,
670                 copy_id => $circ->{circ}->target_copy,
671                 opac_renewal => 1
672             }
673         );
674
675         # TODO return these, then insert them into the circ data 
676         # blob that is shoved into the template for each circ
677         # so the template won't have to match them
678         push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
679     }
680
681     return @responses;
682 }
683
684
685 sub load_myopac_circs {
686     my $self = shift;
687     my $e = $self->editor;
688     my $ctx = $self->ctx;
689
690     $ctx->{circs} = [];
691     my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
692     my $offset = $self->cgi->param('offset') || 0;
693     my $action = $self->cgi->param('action') || '';
694
695     # perform the renewal first if necessary
696     my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
697
698     $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
699
700     my $success_renewals = 0;
701     my $failed_renewals = 0;
702     for my $data (@{$ctx->{circs}}) {
703         my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
704
705         if($resp) {
706             my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
707             $data->{renewal_response} = $evt;
708             $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
709             $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
710         }
711     }
712
713     $ctx->{success_renewals} = $success_renewals;
714     $ctx->{failed_renewals} = $failed_renewals;
715
716     return Apache2::Const::OK;
717 }
718
719 sub load_myopac_circ_history {
720     my $self = shift;
721     my $e = $self->editor;
722     my $ctx = $self->ctx;
723     my $limit = $self->cgi->param('limit') || 15;
724     my $offset = $self->cgi->param('offset') || 0;
725
726     $ctx->{circ_history_limit} = $limit;
727     $ctx->{circ_history_offset} = $offset;
728
729     my $circs = $e->json_query({
730         from => ['action.usr_visible_circs', $e->requestor->id],
731         #limit => $limit || 25,
732         #offset => $offset || 0,
733     });
734
735     # XXX: order-by in the json_query above appears to do nothing, so in-query 
736     # paging is not reallly an option.  do the sorting/paging here
737
738     # sort newest to oldest
739     $circs = [ sort { $b->{xact_start} cmp $a->{xact_start} } @$circs ];
740     my @ids = map { $_->{id} } @$circs;
741
742     # find the selected page and trim cruft
743     @ids = @ids[$offset..($offset + $limit - 1)] if $limit;
744     @ids = grep { defined $_ } @ids;
745
746     $ctx->{circs} = $self->fetch_user_circs(1, \@ids);
747     #$ctx->{circs} = $self->fetch_user_circs(1, [map { $_->{id} } @$circs], $limit, $offset);
748
749     return Apache2::Const::OK;
750 }
751
752 # TODO: action.usr_visible_holds does not return cancelled holds.  Should it?
753 sub load_myopac_hold_history {
754     my $self = shift;
755     my $e = $self->editor;
756     my $ctx = $self->ctx;
757     my $limit = $self->cgi->param('limit') || 15;
758     my $offset = $self->cgi->param('offset') || 0;
759     $ctx->{hold_history_limit} = $limit;
760     $ctx->{hold_history_offset} = $offset;
761
762
763     my $holds = $e->json_query({
764         from => ['action.usr_visible_holds', $e->requestor->id],
765         limit => $limit || 25,
766         offset => $offset || 0
767     });
768
769     $ctx->{holds} = $self->fetch_user_holds([map { $_->{id} } @$holds], 0, 1, 0, $limit, $offset);
770
771     return Apache2::Const::OK;
772 }
773
774 sub load_myopac_payment_form {
775     my $self = shift;
776     my $r;
777
778     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and return $r;
779     $r = $self->prepare_extended_user_info and return $r;
780
781     return Apache2::Const::OK;
782 }
783
784 # TODO: add other filter options as params/configs/etc.
785 sub load_myopac_payments {
786     my $self = shift;
787     my $limit = $self->cgi->param('limit') || 20;
788     my $offset = $self->cgi->param('offset') || 0;
789     my $e = $self->editor;
790
791     $self->ctx->{payment_history_limit} = $limit;
792     $self->ctx->{payment_history_offset} = $offset;
793
794     my $args = {};
795     $args->{limit} = $limit if $limit;
796     $args->{offset} = $offset if $offset;
797
798     if (my $max_age = $self->ctx->{get_org_setting}->(
799         $e->requestor->home_ou, "opac.payment_history_age_limit"
800     )) {
801         my $min_ts = DateTime->now(
802             "time_zone" => DateTime::TimeZone->new("name" => "local"),
803         )->subtract("seconds" => interval_to_seconds($max_age))->iso8601();
804         
805         $logger->info("XXX min_ts: $min_ts");
806         $args->{"where"} = {"payment_ts" => {">=" => $min_ts}};
807     }
808
809     $self->ctx->{payments} = $U->simplereq(
810         'open-ils.actor',
811         'open-ils.actor.user.payments.retrieve.atomic',
812         $e->authtoken, $e->requestor->id, $args);
813
814     return Apache2::Const::OK;
815 }
816
817 sub load_myopac_pay {
818     my $self = shift;
819     my $r;
820
821     $r = $self->prepare_fines(undef, undef, [$self->cgi->param('xact'), $self->cgi->param('xact_misc')]) and
822         return $r;
823
824     # balance_owed is computed specifically from the fines we're trying
825     # to pay in this case.
826     if ($self->ctx->{fines}->{balance_owed} <= 0) {
827         $self->apache->log->info(
828             sprintf("Can't pay non-positive balance. xacts selected: (%s)",
829                 join(", ", map(int, $self->cgi->param("xact"), $self->cgi->param('xact_misc'))))
830         );
831         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
832     }
833
834     my $cc_args = {"where_process" => 1};
835
836     $cc_args->{$_} = $self->cgi->param($_) for (qw/
837         number cvv2 expire_year expire_month billing_first
838         billing_last billing_address billing_city billing_state
839         billing_zip
840     /);
841
842     my $args = {
843         "cc_args" => $cc_args,
844         "userid" => $self->ctx->{user}->id,
845         "payment_type" => "credit_card_payment",
846         "payments" => $self->prepare_fines_for_payment   # should be safe after self->prepare_fines
847     };
848
849     my $resp = $U->simplereq("open-ils.circ", "open-ils.circ.money.payment",
850         $self->editor->authtoken, $args, $self->ctx->{user}->last_xact_id
851     );
852
853     $self->ctx->{"payment_response"} = $resp;
854
855     unless ($resp->{"textcode"}) {
856         $self->ctx->{printable_receipt} = $U->simplereq(
857            "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
858            $self->editor->authtoken, $resp->{payments}
859         );
860     }
861
862     return Apache2::Const::OK;
863 }
864
865 sub load_myopac_receipt_print {
866     my $self = shift;
867
868     $self->ctx->{printable_receipt} = $U->simplereq(
869        "open-ils.circ", "open-ils.circ.money.payment_receipt.print",
870        $self->editor->authtoken, [$self->cgi->param("payment")]
871     );
872
873     return Apache2::Const::OK;
874 }
875
876 sub load_myopac_receipt_email {
877     my $self = shift;
878
879     # The following ML method doesn't actually check whether the user in
880     # question has an email address, so we do.
881     if ($self->ctx->{user}->email) {
882         $self->ctx->{email_receipt_result} = $U->simplereq(
883            "open-ils.circ", "open-ils.circ.money.payment_receipt.email",
884            $self->editor->authtoken, [$self->cgi->param("payment")]
885         );
886     } else {
887         $self->ctx->{email_receipt_result} =
888             new OpenILS::Event("PATRON_NO_EMAIL_ADDRESS");
889     }
890
891     return Apache2::Const::OK;
892 }
893
894 sub prepare_fines {
895     my ($self, $limit, $offset, $id_list) = @_;
896
897     # XXX TODO: check for failure after various network calls
898
899     # It may be unclear, but this result structure lumps circulation and
900     # reservation fines together, and keeps grocery fines separate.
901     $self->ctx->{"fines"} = {
902         "circulation" => [],
903         "grocery" => [],
904         "total_paid" => 0,
905         "total_owed" => 0,
906         "balance_owed" => 0
907     };
908
909     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
910
911     # TODO: This should really be a ML call, but the existing calls 
912     # return an excessive amount of data and don't offer streaming
913
914     my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
915
916     my $req = $cstore->request(
917         'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
918         {
919             usr => $self->editor->requestor->id,
920             balance_owed => {'!=' => 0},
921             ($id_list && @$id_list ? ("id" => $id_list) : ()),
922         },
923         {
924             flesh => 4,
925             flesh_fields => {
926                 mobts => [qw/grocery circulation reservation/],
927                 bresv => ['target_resource_type'],
928                 brt => ['record'],
929                 mg => ['billings'],
930                 mb => ['btype'],
931                 circ => ['target_copy'],
932                 acp => ['call_number'],
933                 acn => ['record']
934             },
935             order_by => { mobts => 'xact_start' },
936             %paging
937         }
938     );
939
940     my @total_keys = qw/total_paid total_owed balance_owed/;
941     $self->ctx->{"fines"}->{@total_keys} = (0, 0, 0);
942
943     while(my $resp = $req->recv) {
944         my $mobts = $resp->content;
945         my $circ = $mobts->circulation;
946
947         my $last_billing;
948         if($mobts->grocery) {
949             my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
950             $last_billing = pop(@billings);
951         }
952
953         # XXX TODO confirm that the following, and the later division by 100.0
954         # to get a floating point representation once again, is sufficiently
955         # "money-safe" math.
956         $self->ctx->{"fines"}->{$_} += int($mobts->$_ * 100) for (@total_keys);
957
958         my $marc_xml = undef;
959         if ($mobts->xact_type eq 'reservation' and
960             $mobts->reservation->target_resource_type->record) {
961             $marc_xml = XML::LibXML->new->parse_string(
962                 $mobts->reservation->target_resource_type->record->marc
963             );
964         } elsif ($mobts->xact_type eq 'circulation' and
965             $circ->target_copy->call_number->id != -1) {
966             $marc_xml = XML::LibXML->new->parse_string(
967                 $circ->target_copy->call_number->record->marc
968             );
969         }
970
971         push(
972             @{$self->ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
973             {
974                 xact => $mobts,
975                 last_grocery_billing => $last_billing,
976                 marc_xml => $marc_xml
977             } 
978         );
979     }
980
981     $cstore->kill_me;
982
983     $self->ctx->{"fines"}->{$_} /= 100.0 for (@total_keys);
984     return;
985 }
986
987 sub prepare_fines_for_payment {
988     # This assumes $self->prepare_fines has already been run
989     my ($self) = @_;
990
991     my @results = ();
992     if ($self->ctx->{fines}) {
993         push @results, [$_->{xact}->id, $_->{xact}->balance_owed] foreach (
994             @{$self->ctx->{fines}->{circulation}},
995             @{$self->ctx->{fines}->{grocery}}
996         );
997     }
998
999     return \@results;
1000 }
1001
1002 sub load_myopac_main {
1003     my $self = shift;
1004     my $limit = $self->cgi->param('limit') || 0;
1005     my $offset = $self->cgi->param('offset') || 0;
1006
1007     return $self->prepare_fines($limit, $offset) || Apache2::Const::OK;
1008 }
1009
1010 sub load_myopac_update_email {
1011     my $self = shift;
1012     my $e = $self->editor;
1013     my $ctx = $self->ctx;
1014     my $email = $self->cgi->param('email') || '';
1015
1016     # needed for most up-to-date email address
1017     if (my $r = $self->prepare_extended_user_info) { return $r };
1018
1019     return Apache2::Const::OK 
1020         unless $self->cgi->request_method eq 'POST';
1021
1022     unless($email =~ /.+\@.+\..+/) { # TODO better regex?
1023         $ctx->{invalid_email} = $email;
1024         return Apache2::Const::OK;
1025     }
1026
1027     my $stat = $U->simplereq(
1028         'open-ils.actor', 
1029         'open-ils.actor.user.email.update', 
1030         $e->authtoken, $email);
1031
1032     unless ($self->cgi->param("redirect_to")) {
1033         my $url = $self->apache->unparsed_uri;
1034         $url =~ s/update_email/prefs/;
1035
1036         return $self->generic_redirect($url);
1037     }
1038
1039     return $self->generic_redirect;
1040 }
1041
1042 sub load_myopac_update_username {
1043     my $self = shift;
1044     my $e = $self->editor;
1045     my $ctx = $self->ctx;
1046     my $username = $self->cgi->param('username') || '';
1047
1048     return Apache2::Const::OK 
1049         unless $self->cgi->request_method eq 'POST';
1050
1051     unless($username and $username !~ /\s/) { # any other username restrictions?
1052         $ctx->{invalid_username} = $username;
1053         return Apache2::Const::OK;
1054     }
1055
1056     if($username ne $e->requestor->usrname) {
1057
1058         my $evt = $U->simplereq(
1059             'open-ils.actor', 
1060             'open-ils.actor.user.username.update', 
1061             $e->authtoken, $username);
1062
1063         if($U->event_equals($evt, 'USERNAME_EXISTS')) {
1064             $ctx->{username_exists} = $username;
1065             return Apache2::Const::OK;
1066         }
1067     }
1068
1069     my $url = $self->apache->unparsed_uri;
1070     $url =~ s/update_username/prefs/;
1071
1072     return $self->generic_redirect($url);
1073 }
1074
1075 sub load_myopac_update_password {
1076     my $self = shift;
1077     my $e = $self->editor;
1078     my $ctx = $self->ctx;
1079
1080     return Apache2::Const::OK 
1081         unless $self->cgi->request_method eq 'POST';
1082
1083     my $current_pw = $self->cgi->param('current_pw') || '';
1084     my $new_pw = $self->cgi->param('new_pw') || '';
1085     my $new_pw2 = $self->cgi->param('new_pw2') || '';
1086
1087     unless($new_pw eq $new_pw2) {
1088         $ctx->{password_nomatch} = 1;
1089         return Apache2::Const::OK;
1090     }
1091
1092     my $pw_regex = $ctx->{get_org_setting}->($e->requestor->home_ou, 'global.password_regex');
1093
1094     if($pw_regex and $new_pw !~ /$pw_regex/) {
1095         $ctx->{password_invalid} = 1;
1096         return Apache2::Const::OK;
1097     }
1098
1099     my $evt = $U->simplereq(
1100         'open-ils.actor', 
1101         'open-ils.actor.user.password.update', 
1102         $e->authtoken, $new_pw, $current_pw);
1103
1104
1105     if($U->event_equals($evt, 'INCORRECT_PASSWORD')) {
1106         $ctx->{password_incorrect} = 1;
1107         return Apache2::Const::OK;
1108     }
1109
1110     my $url = $self->apache->unparsed_uri;
1111     $url =~ s/update_password/prefs/;
1112
1113     return $self->generic_redirect($url);
1114 }
1115
1116 sub load_myopac_bookbags {
1117     my $self = shift;
1118     my $e = $self->editor;
1119     my $ctx = $self->ctx;
1120
1121     $e->xact_begin; # replication...
1122
1123     my $rv = $self->load_mylist;
1124     unless($rv eq Apache2::Const::OK) {
1125         $e->rollback;
1126         return $rv;
1127     }
1128
1129     my $args = {
1130         order_by => {cbreb => 'name'},
1131         limit => $self->cgi->param('limit') || 10,
1132         offset => $self->cgi->param('offset') || 0
1133     };
1134
1135     $ctx->{bookbags} = $e->search_container_biblio_record_entry_bucket([
1136         {owner => $self->editor->requestor->id, btype => 'bookbag'},
1137         # XXX what to do about the possibility of really large bookbags here?
1138         {"flesh" => 1, "flesh_fields" => {"cbreb" => ["items"]}, %$args}
1139     ]);
1140
1141     if(!$ctx->{bookbags}) {
1142         $e->rollback;
1143         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
1144     }
1145     
1146     # get unique record IDs
1147     my %rec_ids = ();
1148     foreach my $bbag (@{$ctx->{bookbags}}) {
1149         foreach my $rec_id (
1150             map { $_->target_biblio_record_entry } @{$bbag->items}
1151         ) {
1152             $rec_ids{$rec_id} = 1;
1153         }
1154     }
1155
1156     $ctx->{bookbags_marc_xml} = $self->fetch_marc_xml_by_id([keys %rec_ids]);
1157
1158     $e->rollback;
1159     return Apache2::Const::OK;
1160 }
1161
1162
1163 # actions are create, delete, show, hide, rename, add_rec, delete_item
1164 # CGI is action, list=list_id, add_rec/record=bre_id, del_item=bucket_item_id, name=new_bucket_name
1165 sub load_myopac_bookbag_update {
1166     my ($self, $action, $list_id) = @_;
1167     my $e = $self->editor;
1168     my $cgi = $self->cgi;
1169
1170     $action ||= $cgi->param('action');
1171     $list_id ||= $cgi->param('list');
1172
1173     my @add_rec = $cgi->param('add_rec') || $cgi->param('record');
1174     my @del_item = $cgi->param('del_item');
1175     my $shared = $cgi->param('shared');
1176     my $name = $cgi->param('name');
1177     my $success = 0;
1178     my $list;
1179
1180     if($action eq 'create') {
1181         $list = Fieldmapper::container::biblio_record_entry_bucket->new;
1182         $list->name($name);
1183         $list->owner($e->requestor->id);
1184         $list->btype('bookbag');
1185         $list->pub($shared ? 't' : 'f');
1186         $success = $U->simplereq('open-ils.actor', 
1187             'open-ils.actor.container.create', $e->authtoken, 'biblio', $list)
1188
1189     } else {
1190
1191         $list = $e->retrieve_container_biblio_record_entry_bucket($list_id);
1192
1193         return Apache2::Const::HTTP_BAD_REQUEST unless 
1194             $list and $list->owner == $e->requestor->id;
1195     }
1196
1197     if($action eq 'delete') {
1198         $success = $U->simplereq('open-ils.actor', 
1199             'open-ils.actor.container.full_delete', $e->authtoken, 'biblio', $list_id);
1200
1201     } elsif($action eq 'show') {
1202         unless($U->is_true($list->pub)) {
1203             $list->pub('t');
1204             $success = $U->simplereq('open-ils.actor', 
1205                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1206         }
1207
1208     } elsif($action eq 'hide') {
1209         if($U->is_true($list->pub)) {
1210             $list->pub('f');
1211             $success = $U->simplereq('open-ils.actor', 
1212                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1213         }
1214
1215     } elsif($action eq 'rename') {
1216         if($name) {
1217             $list->name($name);
1218             $success = $U->simplereq('open-ils.actor', 
1219                 'open-ils.actor.container.update', $e->authtoken, 'biblio', $list);
1220         }
1221
1222     } elsif($action eq 'add_rec') {
1223         foreach my $add_rec (@add_rec) {
1224             my $item = Fieldmapper::container::biblio_record_entry_bucket_item->new;
1225             $item->bucket($list_id);
1226             $item->target_biblio_record_entry($add_rec);
1227             $success = $U->simplereq('open-ils.actor', 
1228                 'open-ils.actor.container.item.create', $e->authtoken, 'biblio', $item);
1229             last unless $success;
1230         }
1231
1232     } elsif($action eq 'del_item') {
1233         foreach (@del_item) {
1234             $success = $U->simplereq(
1235                 'open-ils.actor',
1236                 'open-ils.actor.container.item.delete', $e->authtoken, 'biblio', $_
1237             );
1238             last unless $success;
1239         }
1240     }
1241
1242     return $self->generic_redirect if $success;
1243
1244     $self->ctx->{bucket_action} = $action;
1245     $self->ctx->{bucket_action_failed} = 1;
1246     return Apache2::Const::OK;
1247 }
1248
1249 1