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