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