]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Actor.pm
typos
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Actor.pm
1 package OpenILS::Application::Actor;
2 use base qw/OpenSRF::Application/;
3 use strict; use warnings;
4 use Data::Dumper;
5 $Data::Dumper::Indent = 0;
6 use OpenILS::Event;
7
8 use Digest::MD5 qw(md5_hex);
9
10 use OpenSRF::EX qw(:try);
11 use OpenILS::Perm;
12
13 use OpenILS::Application::AppUtils;
14
15 use OpenILS::Utils::Fieldmapper;
16 use OpenILS::Utils::ModsParser;
17 use OpenSRF::Utils::Logger qw/$logger/;
18 use OpenSRF::Utils qw/:datetime/;
19
20 use OpenSRF::Utils::Cache;
21
22 use JSON;
23 use DateTime;
24 use DateTime::Format::ISO8601;
25 use OpenILS::Const qw/:const/;
26
27 use OpenILS::Application::Actor::Container;
28 use OpenILS::Application::Actor::ClosedDates;
29
30 use OpenILS::Utils::CStoreEditor qw/:funcs/;
31
32 use OpenILS::Application::Actor::UserGroups;
33 sub initialize {
34         OpenILS::Application::Actor::Container->initialize();
35         OpenILS::Application::Actor::UserGroups->initialize();
36         OpenILS::Application::Actor::ClosedDates->initialize();
37 }
38
39 my $apputils = "OpenILS::Application::AppUtils";
40 my $U = $apputils;
41
42 sub _d { warn "Patron:\n" . Dumper(shift()); }
43
44 my $cache;
45
46
47 my $set_user_settings;
48 my $set_ou_settings;
49
50 __PACKAGE__->register_method(
51         method  => "set_user_settings",
52         api_name        => "open-ils.actor.patron.settings.update",
53 );
54 sub set_user_settings {
55         my( $self, $client, $user_session, $uid, $settings ) = @_;
56         
57         $logger->debug("Setting user settings: $user_session, $uid, " . Dumper($settings));
58
59         my( $staff, $user, $evt ) = 
60                 $apputils->checkses_requestor( $user_session, $uid, 'UPDATE_USER' );    
61         return $evt if $evt;
62         
63         my @params = map { 
64                 [{ usr => $user->id, name => $_}, {value => $$settings{$_}}] } keys %$settings;
65                 
66         $_->[1]->{value} = JSON->perl2JSON($_->[1]->{value}) for @params;
67
68         $logger->activity("User " . $staff->id . " updating user $uid settings with: " . Dumper(\@params));
69
70         my $ses = $U->start_db_session();
71         my $stat = $ses->request(
72                 'open-ils.storage.direct.actor.user_setting.batch.merge', @params )->gather(1);
73         $U->commit_db_session($ses);
74
75         return $stat;
76 }
77
78
79
80 __PACKAGE__->register_method(
81         method  => "set_ou_settings",
82         api_name        => "open-ils.actor.org_unit.settings.update",
83 );
84 sub set_ou_settings {
85         my( $self, $client, $user_session, $ouid, $settings ) = @_;
86         
87         my( $staff, $evt ) = $apputils->checkses( $user_session );
88         return $evt if $evt;
89         $evt = $apputils->check_perms( $staff->id, $ouid, 'UPDATE_ORG_SETTING' );
90         return $evt if $evt;
91
92         my @params;
93         for my $set (keys %$settings) {
94
95                 my $json = JSON->perl2JSON($$settings{$set});
96                 $logger->activity("updating org_unit.setting: $ouid : $set : $json");
97
98                 push( @params, 
99                         { org_unit => $ouid, name => $set }, 
100                         { value => $json } );
101         }
102
103         my $ses = $U->start_db_session();
104         my $stat = $ses->request(
105                 'open-ils.storage.direct.actor.org_unit_setting.merge', @params )->gather(1);
106         $U->commit_db_session($ses);
107
108         return $stat;
109 }
110
111
112 my $fetch_user_settings;
113 my $fetch_ou_settings;
114
115 __PACKAGE__->register_method(
116         method  => "user_settings",
117         api_name        => "open-ils.actor.patron.settings.retrieve",
118 );
119 sub user_settings {
120         my( $self, $client, $user_session, $uid ) = @_;
121         
122         my( $staff, $user, $evt ) = 
123                 $apputils->checkses_requestor( $user_session, $uid, 'VIEW_USER' );
124         return $evt if $evt;
125
126         $logger->debug("User " . $staff->id . " fetching user $uid\n");
127         my $s = $apputils->simplereq(
128                 'open-ils.cstore',
129                 'open-ils.cstore.direct.actor.user_setting.search.atomic', { usr => $uid } );
130
131         return { map { ( $_->name => JSON->JSON2perl($_->value) ) } @$s };
132 }
133
134
135
136 __PACKAGE__->register_method(
137         method  => "ou_settings",
138         api_name        => "open-ils.actor.org_unit.settings.retrieve",
139 );
140 sub ou_settings {
141         my( $self, $client, $ouid ) = @_;
142         
143         $logger->info("Fetching org unit settings for org $ouid");
144
145         my $s = $apputils->simplereq(
146                 'open-ils.cstore',
147                 'open-ils.cstore.direct.actor.org_unit_setting.search.atomic', {org_unit => $ouid});
148
149         return { map { ( $_->name => JSON->JSON2perl($_->value) ) } @$s };
150 }
151
152 __PACKAGE__->register_method (
153         method          => "ou_setting_delete",
154         api_name                => 'open-ils.actor.org_setting.delete',
155         signature       => q/
156                 Deletes a specific org unit setting for a specific location
157                 @param authtoken The login session key
158                 @param orgid The org unit whose setting we're changing
159                 @param setting The name of the setting to delete
160                 @return True value on success.
161         /
162 );
163
164 sub ou_setting_delete {
165         my( $self, $conn, $authtoken, $orgid, $setting ) = @_;
166         my( $reqr, $evt) = $U->checkses($authtoken);
167         return $evt if $evt;
168         $evt = $U->check_perms($reqr->id, $orgid, 'UPDATE_ORG_SETTING');
169         return $evt if $evt;
170
171         my $id = $U->cstorereq(
172                 'open-ils.cstore.direct.actor.org_unit_setting.id_list', 
173                 { name => $setting, org_unit => $orgid } );
174
175         $logger->debug("Retrieved setting $id in org unit setting delete");
176
177         my $s = $U->cstorereq(
178                 'open-ils.cstore.direct.actor.org_unit_setting.delete', $id );
179
180         $logger->activity("User ".$reqr->id." deleted org unit setting $id") if $s;
181         return $s;
182 }
183
184
185
186 __PACKAGE__->register_method(
187         method  => "update_patron",
188         api_name        => "open-ils.actor.patron.update",);
189
190 sub update_patron {
191         my( $self, $client, $user_session, $patron ) = @_;
192
193         my $session = $apputils->start_db_session();
194         my $err = undef;
195
196         $logger->info("Creating new patron...") if $patron->isnew; 
197         $logger->info("Updating Patron: " . $patron->id) unless $patron->isnew;
198
199         my( $user_obj, $evt ) = $U->checkses($user_session);
200         return $evt if $evt;
201
202         # XXX does this user have permission to add/create users.  Granularity?
203         # $new_patron is the patron in progress.  $patron is the original patron
204         # passed in with the method.  new_patron will change as the components
205         # of patron are added/updated.
206
207         my $new_patron;
208
209         # unflesh the real items on the patron
210         $patron->card( $patron->card->id ) if(ref($patron->card));
211         $patron->billing_address( $patron->billing_address->id ) 
212                 if(ref($patron->billing_address));
213         $patron->mailing_address( $patron->mailing_address->id ) 
214                 if(ref($patron->mailing_address));
215
216         # create/update the patron first so we can use his id
217         if($patron->isnew()) {
218                 ( $new_patron, $evt ) = _add_patron($session, _clone_patron($patron), $user_obj);
219                 return $evt if $evt;
220         } else { $new_patron = $patron; }
221
222         ( $new_patron, $evt ) = _add_update_addresses($session, $patron, $new_patron, $user_obj);
223         return $evt if $evt;
224
225         ( $new_patron, $evt ) = _add_update_cards($session, $patron, $new_patron, $user_obj);
226         return $evt if $evt;
227
228         ( $new_patron, $evt ) = _add_survey_responses($session, $patron, $new_patron, $user_obj);
229         return $evt if $evt;
230
231         # re-update the patron if anything has happened to him during this process
232         if($new_patron->ischanged()) {
233                 ( $new_patron, $evt ) = _update_patron($session, $new_patron, $user_obj);
234                 return $evt if $evt;
235         }
236
237         #$session = OpenSRF::AppSession->create("open-ils.storage");  # why did i put this here?
238
239         ($new_patron, $evt) = _create_stat_maps($session, $user_session, $patron, $new_patron, $user_obj);
240         return $evt if $evt;
241
242         ($new_patron, $evt) = _create_perm_maps($session, $user_session, $patron, $new_patron, $user_obj);
243         return $evt if $evt;
244
245         ($new_patron, $evt) = _create_standing_penalties($session, $user_session, $patron, $new_patron, $user_obj);
246         return $evt if $evt;
247
248         $logger->activity("user ".$user_obj->id." updating/creating  user ".$new_patron->id);
249
250         my $opatron;
251         if(!$patron->isnew) {
252                 $opatron = new_editor()->retrieve_actor_user($new_patron->id);
253         }
254
255         $apputils->commit_db_session($session);
256         my $fuser =  flesh_user($new_patron->id());
257
258         if( $opatron ) {
259                 # Log the new and old patron for investigation
260                 $logger->info("$user_session updating patron object. orig patron object = ".
261                         JSON->perl2JSON($opatron). " |||| new patron = ".JSON->perl2JSON($fuser));
262         }
263
264
265         return $fuser;
266 }
267
268
269 sub flesh_user {
270         my $id = shift;
271         return new_flesh_user($id, [
272                 "cards",
273                 "card",
274                 "standing_penalties",
275                 "addresses",
276                 "billing_address",
277                 "mailing_address",
278                 "stat_cat_entries" ] );
279 }
280
281
282
283
284
285
286 # clone and clear stuff that would break the database
287 sub _clone_patron {
288         my $patron = shift;
289
290         my $new_patron = $patron->clone;
291         # clear these
292         $new_patron->clear_billing_address();
293         $new_patron->clear_mailing_address();
294         $new_patron->clear_addresses();
295         $new_patron->clear_card();
296         $new_patron->clear_cards();
297         $new_patron->clear_id();
298         $new_patron->clear_isnew();
299         $new_patron->clear_ischanged();
300         $new_patron->clear_isdeleted();
301         $new_patron->clear_stat_cat_entries();
302         $new_patron->clear_permissions();
303         $new_patron->clear_standing_penalties();
304
305         return $new_patron;
306 }
307
308
309 sub _add_patron {
310
311         my $session             = shift;
312         my $patron              = shift;
313         my $user_obj    = shift;
314
315         my $evt = $U->check_perms($user_obj->id, $patron->home_ou, 'CREATE_USER');
316         return (undef, $evt) if $evt;
317
318         my $ex = $session->request(
319                 'open-ils.storage.direct.actor.user.search.usrname', $patron->usrname())->gather(1);
320         if( $ex and @$ex ) {
321                 return (undef, OpenILS::Event->new('USERNAME_EXISTS'));
322         }
323
324         $logger->info("Creating new user in the DB with username: ".$patron->usrname());
325
326         my $id = $session->request(
327                 "open-ils.storage.direct.actor.user.create", $patron)->gather(1);
328         return (undef, $U->DB_UPDATE_FAILED($patron)) unless $id;
329
330         $logger->info("Successfully created new user [$id] in DB");
331
332         return ( $session->request( 
333                 "open-ils.storage.direct.actor.user.retrieve", $id)->gather(1), undef );
334 }
335
336
337 sub _update_patron {
338         my( $session, $patron, $user_obj, $noperm) = @_;
339
340         $logger->info("Updating patron ".$patron->id." in DB");
341
342         my $evt;
343
344         if(!$noperm) {
345                 $evt = $U->check_perms($user_obj->id, $patron->home_ou, 'UPDATE_USER');
346                 return (undef, $evt) if $evt;
347         }
348
349         # update the password by itself to avoid the password protection magic
350         if( $patron->passwd ) {
351                 my $s = $session->request(
352                         'open-ils.storage.direct.actor.user.remote_update',
353                         {id => $patron->id}, {passwd => $patron->passwd})->gather(1);
354                 return (undef, $U->DB_UPDATE_FAILED($patron)) unless defined($s);
355                 $patron->clear_passwd;
356         }
357
358         if(!$patron->ident_type) {
359                 $patron->clear_ident_type;
360                 $patron->clear_ident_value;
361         }
362
363         my $stat = $session->request(
364                 "open-ils.storage.direct.actor.user.update",$patron )->gather(1);
365         return (undef, $U->DB_UPDATE_FAILED($patron)) unless defined($stat);
366
367         return ($patron);
368 }
369
370 sub _check_dup_ident {
371         my( $session, $patron ) = @_;
372
373         return undef unless $patron->ident_value;
374
375         my $search = {
376                 ident_type      => $patron->ident_type, 
377                 ident_value => $patron->ident_value,
378         };
379
380         $logger->debug("patron update searching for dup ident values: " . 
381                 $patron->ident_type . ':' . $patron->ident_value);
382
383         $search->{id} = {'!=' => $patron->id} if $patron->id and $patron->id > 0;
384
385         my $dups = $session->request(
386                 'open-ils.storage.direct.actor.user.search_where.atomic', $search )->gather(1);
387
388
389         return OpenILS::Event->new('PATRON_DUP_IDENT1', payload => $patron )
390                 if $dups and @$dups;
391
392         return undef;
393 }
394
395
396 sub _add_update_addresses {
397
398         my $session = shift;
399         my $patron = shift;
400         my $new_patron = shift;
401
402         my $evt;
403
404         my $current_id; # id of the address before creation
405
406         for my $address (@{$patron->addresses()}) {
407
408                 next unless ref $address;
409                 $current_id = $address->id();
410
411                 if( $patron->billing_address() and
412                         $patron->billing_address() == $current_id ) {
413                         $logger->info("setting billing addr to $current_id");
414                         $new_patron->billing_address($address->id());
415                         $new_patron->ischanged(1);
416                 }
417         
418                 if( $patron->mailing_address() and
419                         $patron->mailing_address() == $current_id ) {
420                         $new_patron->mailing_address($address->id());
421                         $logger->info("setting mailing addr to $current_id");
422                         $new_patron->ischanged(1);
423                 }
424
425
426                 if($address->isnew()) {
427
428                         $address->usr($new_patron->id());
429
430                         ($address, $evt) = _add_address($session,$address);
431                         return (undef, $evt) if $evt;
432
433                         # we need to get the new id
434                         if( $patron->billing_address() and 
435                                         $patron->billing_address() == $current_id ) {
436                                 $new_patron->billing_address($address->id());
437                                 $logger->info("setting billing addr to $current_id");
438                                 $new_patron->ischanged(1);
439                         }
440
441                         if( $patron->mailing_address() and
442                                         $patron->mailing_address() == $current_id ) {
443                                 $new_patron->mailing_address($address->id());
444                                 $logger->info("setting mailing addr to $current_id");
445                                 $new_patron->ischanged(1);
446                         }
447
448                 } elsif($address->ischanged() ) {
449
450                         ($address, $evt) = _update_address($session, $address);
451                         return (undef, $evt) if $evt;
452
453                 } elsif($address->isdeleted() ) {
454
455                         if( $address->id() == $new_patron->mailing_address() ) {
456                                 $new_patron->clear_mailing_address();
457                                 ($new_patron, $evt) = _update_patron($session, $new_patron);
458                                 return (undef, $evt) if $evt;
459                         }
460
461                         if( $address->id() == $new_patron->billing_address() ) {
462                                 $new_patron->clear_billing_address();
463                                 ($new_patron, $evt) = _update_patron($session, $new_patron);
464                                 return (undef, $evt) if $evt;
465                         }
466
467                         $evt = _delete_address($session, $address);
468                         return (undef, $evt) if $evt;
469                 } 
470         }
471
472         return ( $new_patron, undef );
473 }
474
475
476 # adds an address to the db and returns the address with new id
477 sub _add_address {
478         my($session, $address) = @_;
479         $address->clear_id();
480
481         $logger->info("Creating new address at street ".$address->street1);
482
483         # put the address into the database
484         my $id = $session->request(
485                 "open-ils.storage.direct.actor.user_address.create", $address )->gather(1);
486         return (undef, $U->DB_UPDATE_FAILED($address)) unless $id;
487
488         $address->id( $id );
489         return ($address, undef);
490 }
491
492
493 sub _update_address {
494         my( $session, $address ) = @_;
495
496         $logger->info("Updating address ".$address->id." in the DB");
497
498         my $stat = $session->request(
499                 "open-ils.storage.direct.actor.user_address.update", $address )->gather(1);
500
501         return (undef, $U->DB_UPDATE_FAILED($address)) unless defined($stat);
502         return ($address, undef);
503 }
504
505
506
507 sub _add_update_cards {
508
509         my $session = shift;
510         my $patron = shift;
511         my $new_patron = shift;
512
513         my $evt;
514
515         my $virtual_id; #id of the card before creation
516         for my $card (@{$patron->cards()}) {
517
518                 $card->usr($new_patron->id());
519
520                 if(ref($card) and $card->isnew()) {
521
522                         $virtual_id = $card->id();
523                         ( $card, $evt ) = _add_card($session,$card);
524                         return (undef, $evt) if $evt;
525
526                         #if(ref($patron->card)) { $patron->card($patron->card->id); }
527                         if($patron->card() == $virtual_id) {
528                                 $new_patron->card($card->id());
529                                 $new_patron->ischanged(1);
530                         }
531
532                 } elsif( ref($card) and $card->ischanged() ) {
533                         $evt = _update_card($session, $card);
534                         return (undef, $evt) if $evt;
535                 }
536         }
537
538         return ( $new_patron, undef );
539 }
540
541
542 # adds an card to the db and returns the card with new id
543 sub _add_card {
544         my( $session, $card ) = @_;
545         $card->clear_id();
546
547         $logger->info("Adding new patron card ".$card->barcode);
548
549         my $id = $session->request(
550                 "open-ils.storage.direct.actor.card.create", $card )->gather(1);
551         return (undef, $U->DB_UPDATE_FAILED($card)) unless $id;
552         $logger->info("Successfully created patron card $id");
553
554         $card->id($id);
555         return ( $card, undef );
556 }
557
558
559 # returns event on error.  returns undef otherwise
560 sub _update_card {
561         my( $session, $card ) = @_;
562         $logger->info("Updating patron card ".$card->id);
563
564         my $stat = $session->request(
565                 "open-ils.storage.direct.actor.card.update", $card )->gather(1);
566         return $U->DB_UPDATE_FAILED($card) unless defined($stat);
567         return undef;
568 }
569
570
571
572
573 # returns event on error.  returns undef otherwise
574 sub _delete_address {
575         my( $session, $address ) = @_;
576
577         $logger->info("Deleting address ".$address->id." from DB");
578
579         my $stat = $session->request(
580                 "open-ils.storage.direct.actor.user_address.delete", $address )->gather(1);
581
582         return $U->DB_UPDATE_FAILED($address) unless defined($stat);
583         return undef;
584 }
585
586
587
588 sub _add_survey_responses {
589         my ($session, $patron, $new_patron) = @_;
590
591         $logger->info( "Updating survey responses for patron ".$new_patron->id );
592
593         my $responses = $patron->survey_responses;
594
595         if($responses) {
596
597                 $_->usr($new_patron->id) for (@$responses);
598
599                 my $evt = $U->simplereq( "open-ils.circ", 
600                         "open-ils.circ.survey.submit.user_id", $responses );
601
602                 return (undef, $evt) if defined($U->event_code($evt));
603
604         }
605
606         return ( $new_patron, undef );
607 }
608
609
610 sub _create_stat_maps {
611
612         my($session, $user_session, $patron, $new_patron) = @_;
613
614         my $maps = $patron->stat_cat_entries();
615
616         for my $map (@$maps) {
617
618                 my $method = "open-ils.storage.direct.actor.stat_cat_entry_user_map.update";
619
620                 if ($map->isdeleted()) {
621                         $method = "open-ils.storage.direct.actor.stat_cat_entry_user_map.delete";
622
623                 } elsif ($map->isnew()) {
624                         $method = "open-ils.storage.direct.actor.stat_cat_entry_user_map.create";
625                         $map->clear_id;
626                 }
627
628
629                 $map->target_usr($new_patron->id);
630
631                 #warn "
632                 $logger->info("Updating stat entry with method $method and map $map");
633
634                 my $stat = $session->request($method, $map)->gather(1);
635                 return (undef, $U->DB_UPDATE_FAILED($map)) unless defined($stat);
636
637         }
638
639         return ($new_patron, undef);
640 }
641
642 sub _create_perm_maps {
643
644         my($session, $user_session, $patron, $new_patron) = @_;
645
646         my $maps = $patron->permissions;
647
648         for my $map (@$maps) {
649
650                 my $method = "open-ils.storage.direct.permission.usr_perm_map.update";
651                 if ($map->isdeleted()) {
652                         $method = "open-ils.storage.direct.permission.usr_perm_map.delete";
653                 } elsif ($map->isnew()) {
654                         $method = "open-ils.storage.direct.permission.usr_perm_map.create";
655                         $map->clear_id;
656                 }
657
658
659                 $map->usr($new_patron->id);
660
661                 #warn( "Updating permissions with method $method and session $user_session and map $map" );
662                 $logger->info( "Updating permissions with method $method and map $map" );
663
664                 my $stat = $session->request($method, $map)->gather(1);
665                 return (undef, $U->DB_UPDATE_FAILED($map)) unless defined($stat);
666
667         }
668
669         return ($new_patron, undef);
670 }
671
672
673 sub _create_standing_penalties {
674
675         my($session, $user_session, $patron, $new_patron) = @_;
676
677         my $maps = $patron->standing_penalties;
678         my $method;
679
680         for my $map (@$maps) {
681
682                 if ($map->isdeleted()) {
683                         $method = "open-ils.storage.direct.actor.user_standing_penalty.delete";
684                 } elsif ($map->isnew()) {
685                         $method = "open-ils.storage.direct.actor.user_standing_penalty.create";
686                         $map->clear_id;
687                 } else {
688                         next;
689                 }
690
691                 $map->usr($new_patron->id);
692
693                 $logger->debug( "Updating standing penalty with method $method and session $user_session and map $map" );
694
695                 my $stat = $session->request($method, $map)->gather(1);
696                 return (undef, $U->DB_UPDATE_FAILED($map)) unless $stat;
697         }
698
699         return ($new_patron, undef);
700 }
701
702
703
704 __PACKAGE__->register_method(
705         method  => "search_username",
706         api_name        => "open-ils.actor.user.search.username",
707 );
708
709 sub search_username {
710         my($self, $client, $username) = @_;
711         my $users = OpenILS::Application::AppUtils->simple_scalar_request(
712                         "open-ils.cstore", 
713                         "open-ils.cstore.direct.actor.user.search.atomic",
714                         { usrname => $username }
715         );
716         return $users;
717 }
718
719
720
721
722 __PACKAGE__->register_method(
723         method  => "user_retrieve_by_barcode",
724         api_name        => "open-ils.actor.user.fleshed.retrieve_by_barcode",);
725
726 sub user_retrieve_by_barcode {
727         my($self, $client, $user_session, $barcode) = @_;
728
729         $logger->debug("Searching for user with barcode $barcode");
730         my ($user_obj, $evt) = $apputils->checkses($user_session);
731         return $evt if $evt;
732
733         my $card = OpenILS::Application::AppUtils->simple_scalar_request(
734                         "open-ils.cstore", 
735                         "open-ils.cstore.direct.actor.card.search.atomic",
736                         { barcode => $barcode }
737         );
738
739         if(!$card || !$card->[0]) {
740                 return OpenILS::Event->new( 'ACTOR_USER_NOT_FOUND' );
741         }
742
743         $card = $card->[0];
744         my $user = flesh_user($card->usr());
745
746         $evt = $U->check_perms($user_obj->id, $user->home_ou, 'VIEW_USER');
747         return $evt if $evt;
748
749         if(!$user) { return OpenILS::Event->new( 'ACTOR_USER_NOT_FOUND' ); }
750         return $user;
751
752 }
753
754
755
756 __PACKAGE__->register_method(
757         method  => "get_user_by_id",
758         api_name        => "open-ils.actor.user.retrieve",);
759
760 sub get_user_by_id {
761         my ($self, $client, $auth, $id) = @_;
762         my $e = new_editor(authtoken=>$auth);
763         return $e->event unless $e->checkauth;
764         my $user = $e->retrieve_actor_user($id)
765                 or return $e->event;
766         return $e->event unless $e->allowed('VIEW_USER', $user->home_ou);       
767         return $user;
768 }
769
770
771
772 __PACKAGE__->register_method(
773         method  => "get_org_types",
774         api_name        => "open-ils.actor.org_types.retrieve",);
775
776 my $org_types;
777 sub get_org_types {
778         my($self, $client) = @_;
779         return $org_types if $org_types;
780         return $org_types = new_editor()->retrieve_all_actor_org_unit_type();
781 }
782
783
784
785 __PACKAGE__->register_method(
786         method  => "get_user_ident_types",
787         api_name        => "open-ils.actor.user.ident_types.retrieve",
788 );
789 my $ident_types;
790 sub get_user_ident_types {
791         return $ident_types if $ident_types;
792         return $ident_types = 
793                 new_editor()->retrieve_all_config_identification_type();
794 }
795
796
797
798
799 __PACKAGE__->register_method(
800         method  => "get_org_unit",
801         api_name        => "open-ils.actor.org_unit.retrieve",
802 );
803
804 sub get_org_unit {
805         my( $self, $client, $user_session, $org_id ) = @_;
806         my $e = new_editor(authtoken => $user_session);
807         if(!$org_id) {
808                 return $e->event unless $e->checkauth;
809                 $org_id = $e->requestor->ws_ou;
810         }
811         my $o = $e->retrieve_actor_org_unit($org_id)
812                 or return $e->event;
813         return $o;
814 }
815
816 __PACKAGE__->register_method(
817         method  => "search_org_unit",
818         api_name        => "open-ils.actor.org_unit_list.search",
819 );
820
821 sub search_org_unit {
822
823         my( $self, $client, $field, $value ) = @_;
824
825         my $list = OpenILS::Application::AppUtils->simple_scalar_request(
826                 "open-ils.cstore",
827                 "open-ils.cstore.direct.actor.org_unit.search.atomic", 
828                 { $field => $value } );
829
830         return $list;
831 }
832
833
834 # build the org tree
835
836 __PACKAGE__->register_method(
837         method  => "get_org_tree",
838         api_name        => "open-ils.actor.org_tree.retrieve",
839         argc            => 0, 
840         note            => "Returns the entire org tree structure",
841 );
842
843 sub get_org_tree {
844         my( $self, $client) = @_;
845
846         $cache  = OpenSRF::Utils::Cache->new("global", 0) unless $cache;
847         my $tree = $cache->get_cache('orgtree');
848         return $tree if $tree;
849
850         $tree = new_editor()->search_actor_org_unit( 
851                 [
852                         {"parent_ou" => undef },
853                         {
854                                 flesh                           => 2,
855                                 flesh_fields    => { aou =>  ['children'] },
856                                 order_by                        => { aou => 'name'}
857                         }
858                 ]
859         )->[0];
860
861         $cache->put_cache('orgtree', $tree);
862         return $tree;
863 }
864
865
866 # turns an org list into an org tree
867 sub build_org_tree {
868
869         my( $self, $orglist) = @_;
870
871         return $orglist unless ( 
872                         ref($orglist) and @$orglist > 1 );
873
874         my @list = sort { 
875                 $a->ou_type <=> $b->ou_type ||
876                 $a->name cmp $b->name } @$orglist;
877
878         for my $org (@list) {
879
880                 next unless ($org and defined($org->parent_ou));
881                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
882                 next unless $parent;
883
884                 $parent->children([]) unless defined($parent->children); 
885                 push( @{$parent->children}, $org );
886         }
887
888         return $list[0];
889
890 }
891
892
893 __PACKAGE__->register_method(
894         method  => "get_org_descendants",
895         api_name        => "open-ils.actor.org_tree.descendants.retrieve"
896 );
897
898 # depth is optional.  org_unit is the id
899 sub get_org_descendants {
900         my( $self, $client, $org_unit, $depth ) = @_;
901         my $orglist = $apputils->simple_scalar_request(
902                         "open-ils.storage", 
903                         "open-ils.storage.actor.org_unit.descendants.atomic",
904                         $org_unit, $depth );
905         return $self->build_org_tree($orglist);
906 }
907
908
909 __PACKAGE__->register_method(
910         method  => "get_org_ancestors",
911         api_name        => "open-ils.actor.org_tree.ancestors.retrieve"
912 );
913
914 # depth is optional.  org_unit is the id
915 sub get_org_ancestors {
916         my( $self, $client, $org_unit, $depth ) = @_;
917         my $orglist = $apputils->simple_scalar_request(
918                         "open-ils.storage", 
919                         "open-ils.storage.actor.org_unit.ancestors.atomic",
920                         $org_unit, $depth );
921         return $self->build_org_tree($orglist);
922 }
923
924
925 __PACKAGE__->register_method(
926         method  => "get_standings",
927         api_name        => "open-ils.actor.standings.retrieve"
928 );
929
930 my $user_standings;
931 sub get_standings {
932         return $user_standings if $user_standings;
933         return $user_standings = 
934                 $apputils->simple_scalar_request(
935                         "open-ils.cstore",
936                         "open-ils.cstore.direct.config.standing.search.atomic",
937                         { id => { "!=" => undef } }
938                 );
939 }
940
941
942
943 __PACKAGE__->register_method(
944         method  => "get_my_org_path",
945         api_name        => "open-ils.actor.org_unit.full_path.retrieve"
946 );
947
948 sub get_my_org_path {
949         my( $self, $client, $user_session, $org_id ) = @_;
950         my $user_obj = $apputils->check_user_session($user_session); 
951         if(!defined($org_id)) { $org_id = $user_obj->home_ou; }
952
953         return $apputils->simple_scalar_request(
954                 "open-ils.storage",
955                 "open-ils.storage.actor.org_unit.full_path.atomic",
956                 $org_id );
957 }
958
959
960 __PACKAGE__->register_method(
961         method  => "patron_adv_search",
962         api_name        => "open-ils.actor.patron.search.advanced" );
963 sub patron_adv_search {
964         my( $self, $client, $auth, $search_hash, $search_limit, $search_sort, $include_inactive ) = @_;
965         my $e = new_editor(authtoken=>$auth);
966         return $e->event unless $e->checkauth;
967         return $e->event unless $e->allowed('VIEW_USER');
968         return $U->storagereq(
969                 "open-ils.storage.actor.user.crazy_search", 
970                 $search_hash, $search_limit, $search_sort, $include_inactive);
971 }
972
973
974
975 sub _verify_password {
976         my($user_session, $password) = @_;
977         my $user_obj = $apputils->check_user_session($user_session); 
978
979         #grab the user with password
980         $user_obj = $apputils->simple_scalar_request(
981                 "open-ils.cstore", 
982                 "open-ils.cstore.direct.actor.user.retrieve",
983                 $user_obj->id );
984
985         if($user_obj->passwd eq $password) {
986                 return 1;
987         }
988
989         return 0;
990 }
991
992
993 __PACKAGE__->register_method(
994         method  => "update_password",
995         api_name        => "open-ils.actor.user.password.update");
996
997 __PACKAGE__->register_method(
998         method  => "update_password",
999         api_name        => "open-ils.actor.user.username.update");
1000
1001 __PACKAGE__->register_method(
1002         method  => "update_password",
1003         api_name        => "open-ils.actor.user.email.update");
1004
1005 sub update_password {
1006         my( $self, $client, $user_session, $new_value, $current_password ) = @_;
1007
1008         my $evt;
1009
1010         my $user_obj = $apputils->check_user_session($user_session); 
1011
1012         if($self->api_name =~ /password/o) {
1013
1014                 #make sure they know the current password
1015                 if(!_verify_password($user_session, md5_hex($current_password))) {
1016                         return OpenILS::Event->new('INCORRECT_PASSWORD');
1017                 }
1018
1019                 $logger->debug("update_password setting new password $new_value");
1020                 $user_obj->passwd($new_value);
1021
1022         } elsif($self->api_name =~ /username/o) {
1023                 my $users = search_username(undef, undef, $new_value); 
1024                 if( $users and $users->[0] ) {
1025                         return OpenILS::Event->new('USERNAME_EXISTS');
1026                 }
1027                 $user_obj->usrname($new_value);
1028
1029         } elsif($self->api_name =~ /email/o) {
1030                 #warn "Updating email to $new_value\n";
1031                 $user_obj->email($new_value);
1032         }
1033
1034         my $session = $apputils->start_db_session();
1035
1036         ( $user_obj, $evt ) = _update_patron($session, $user_obj, $user_obj, 1);
1037         return $evt if $evt;
1038
1039         $apputils->commit_db_session($session);
1040
1041         if($user_obj) { return 1; }
1042         return undef;
1043 }
1044
1045
1046 __PACKAGE__->register_method(
1047         method  => "check_user_perms",
1048         api_name        => "open-ils.actor.user.perm.check",
1049         notes           => <<"  NOTES");
1050         Takes a login session, user id, an org id, and an array of perm type strings.  For each
1051         perm type, if the user does *not* have the given permission it is added
1052         to a list which is returned from the method.  If all permissions
1053         are allowed, an empty list is returned
1054         if the logged in user does not match 'user_id', then the logged in user must
1055         have VIEW_PERMISSION priveleges.
1056         NOTES
1057
1058 sub check_user_perms {
1059         my( $self, $client, $login_session, $user_id, $org_id, $perm_types ) = @_;
1060
1061         my( $staff, $evt ) = $apputils->checkses($login_session);
1062         return $evt if $evt;
1063
1064         if($staff->id ne $user_id) {
1065                 if( $evt = $apputils->check_perms(
1066                         $staff->id, $org_id, 'VIEW_PERMISSION') ) {
1067                         return $evt;
1068                 }
1069         }
1070
1071         my @not_allowed;
1072         for my $perm (@$perm_types) {
1073                 if($apputils->check_perms($user_id, $org_id, $perm)) {
1074                         push @not_allowed, $perm;
1075                 }
1076         }
1077
1078         return \@not_allowed
1079 }
1080
1081 __PACKAGE__->register_method(
1082         method  => "check_user_perms2",
1083         api_name        => "open-ils.actor.user.perm.check.multi_org",
1084         notes           => q/
1085                 Checks the permissions on a list of perms and orgs for a user
1086                 @param authtoken The login session key
1087                 @param user_id The id of the user to check
1088                 @param orgs The array of org ids
1089                 @param perms The array of permission names
1090                 @return An array of  [ orgId, permissionName ] arrays that FAILED the check
1091                 if the logged in user does not match 'user_id', then the logged in user must
1092                 have VIEW_PERMISSION priveleges.
1093         /);
1094
1095 sub check_user_perms2 {
1096         my( $self, $client, $authtoken, $user_id, $orgs, $perms ) = @_;
1097
1098         my( $staff, $target, $evt ) = $apputils->checkses_requestor(
1099                 $authtoken, $user_id, 'VIEW_PERMISSION' );
1100         return $evt if $evt;
1101
1102         my @not_allowed;
1103         for my $org (@$orgs) {
1104                 for my $perm (@$perms) {
1105                         if($apputils->check_perms($user_id, $org, $perm)) {
1106                                 push @not_allowed, [ $org, $perm ];
1107                         }
1108                 }
1109         }
1110
1111         return \@not_allowed
1112 }
1113
1114
1115 __PACKAGE__->register_method(
1116         method => 'check_user_perms3',
1117         api_name        => 'open-ils.actor.user.perm.highest_org',
1118         notes           => q/
1119                 Returns the highest org unit id at which a user has a given permission
1120                 If the requestor does not match the target user, the requestor must have
1121                 'VIEW_PERMISSION' rights at the home org unit of the target user
1122                 @param authtoken The login session key
1123                 @param userid The id of the user in question
1124                 @param perm The permission to check
1125                 @return The org unit highest in the org tree within which the user has
1126                 the requested permission
1127         /);
1128
1129 sub check_user_perms3 {
1130         my( $self, $client, $authtoken, $userid, $perm ) = @_;
1131
1132         my( $staff, $target, $org, $evt );
1133
1134         ( $staff, $target, $evt ) = $apputils->checkses_requestor(
1135                 $authtoken, $userid, 'VIEW_PERMISSION' );
1136         return $evt if $evt;
1137
1138         my $tree = $self->get_org_tree();
1139         return _find_highest_perm_org( $perm, $userid, $target->ws_ou, $tree );
1140 }
1141
1142
1143 sub _find_highest_perm_org {
1144         my ( $perm, $userid, $start_org, $org_tree ) = @_;
1145         my $org = $apputils->find_org($org_tree, $start_org );
1146
1147         my $lastid = undef;
1148         while( $org ) {
1149                 last if ($apputils->check_perms( $userid, $org->id, $perm )); # perm failed
1150                 $lastid = $org->id;
1151                 $org = $apputils->find_org( $org_tree, $org->parent_ou() );
1152         }
1153
1154         return $lastid;
1155 }
1156
1157 __PACKAGE__->register_method(
1158         method => 'check_user_perms4',
1159         api_name        => 'open-ils.actor.user.perm.highest_org.batch',
1160         notes           => q/
1161                 Returns the highest org unit id at which a user has a given permission
1162                 If the requestor does not match the target user, the requestor must have
1163                 'VIEW_PERMISSION' rights at the home org unit of the target user
1164                 @param authtoken The login session key
1165                 @param userid The id of the user in question
1166                 @param perms An array of perm names to check 
1167                 @return An array of orgId's  representing the org unit 
1168                 highest in the org tree within which the user has the requested permission
1169                 The arrah of orgId's has matches the order of the perms array
1170         /);
1171
1172 sub check_user_perms4 {
1173         my( $self, $client, $authtoken, $userid, $perms ) = @_;
1174         
1175         my( $staff, $target, $org, $evt );
1176
1177         ( $staff, $target, $evt ) = $apputils->checkses_requestor(
1178                 $authtoken, $userid, 'VIEW_PERMISSION' );
1179         return $evt if $evt;
1180
1181         my @arr;
1182         return [] unless ref($perms);
1183         my $tree = $self->get_org_tree();
1184
1185         for my $p (@$perms) {
1186                 push( @arr, _find_highest_perm_org( $p, $userid, $target->home_ou, $tree ) );
1187         }
1188         return \@arr;
1189 }
1190
1191
1192
1193
1194 __PACKAGE__->register_method(
1195         method  => "user_fines_summary",
1196         api_name        => "open-ils.actor.user.fines.summary",
1197         notes           => <<"  NOTES");
1198         Returns a short summary of the users total open fines, excluding voided fines
1199         Params are login_session, user_id
1200         Returns a 'mous' object.
1201         NOTES
1202
1203 sub user_fines_summary {
1204         my( $self, $client, $login_session, $user_id ) = @_;
1205
1206         my $user_obj = $apputils->check_user_session($login_session); 
1207         if($user_obj->id ne $user_id) {
1208                 if($apputils->check_user_perms($user_obj->id, $user_obj->home_ou, "VIEW_USER_FINES_SUMMARY")) {
1209                         return OpenILS::Perm->new("VIEW_USER_FINES_SUMMARY"); 
1210                 }
1211         }
1212
1213         return $apputils->simple_scalar_request( 
1214                 "open-ils.cstore",
1215                 "open-ils.cstore.direct.money.open_user_summary.search",
1216                 { usr => $user_id } );
1217
1218 }
1219
1220
1221
1222
1223 __PACKAGE__->register_method(
1224         method  => "user_transactions",
1225         api_name        => "open-ils.actor.user.transactions",
1226         notes           => <<"  NOTES");
1227         Returns a list of open user transactions (mbts objects);
1228         Params are login_session, user_id
1229         Optional third parameter is the transactions type.  defaults to all
1230         NOTES
1231
1232 __PACKAGE__->register_method(
1233         method  => "user_transactions",
1234         api_name        => "open-ils.actor.user.transactions.have_charge",
1235         notes           => <<"  NOTES");
1236         Returns a list of all open user transactions (mbts objects) that have an initial charge
1237         Params are login_session, user_id
1238         Optional third parameter is the transactions type.  defaults to all
1239         NOTES
1240
1241 __PACKAGE__->register_method(
1242         method  => "user_transactions",
1243         api_name        => "open-ils.actor.user.transactions.have_balance",
1244         notes           => <<"  NOTES");
1245         Returns a list of all open user transactions (mbts objects) that have a balance
1246         Params are login_session, user_id
1247         Optional third parameter is the transactions type.  defaults to all
1248         NOTES
1249
1250 __PACKAGE__->register_method(
1251         method  => "user_transactions",
1252         api_name        => "open-ils.actor.user.transactions.fleshed",
1253         notes           => <<"  NOTES");
1254         Returns an object/hash of transaction, circ, title where transaction = an open 
1255         user transactions (mbts objects), circ is the attached circluation, and title
1256         is the title the circ points to
1257         Params are login_session, user_id
1258         Optional third parameter is the transactions type.  defaults to all
1259         NOTES
1260
1261 __PACKAGE__->register_method(
1262         method  => "user_transactions",
1263         api_name        => "open-ils.actor.user.transactions.have_charge.fleshed",
1264         notes           => <<"  NOTES");
1265         Returns an object/hash of transaction, circ, title where transaction = an open 
1266         user transactions that has an initial charge (mbts objects), circ is the 
1267         attached circluation, and title is the title the circ points to
1268         Params are login_session, user_id
1269         Optional third parameter is the transactions type.  defaults to all
1270         NOTES
1271
1272 __PACKAGE__->register_method(
1273         method  => "user_transactions",
1274         api_name        => "open-ils.actor.user.transactions.have_balance.fleshed",
1275         notes           => <<"  NOTES");
1276         Returns an object/hash of transaction, circ, title where transaction = an open 
1277         user transaction that has a balance (mbts objects), circ is the attached 
1278         circluation, and title is the title the circ points to
1279         Params are login_session, user_id
1280         Optional third parameter is the transaction type.  defaults to all
1281         NOTES
1282
1283 __PACKAGE__->register_method(
1284         method  => "user_transactions",
1285         api_name        => "open-ils.actor.user.transactions.count",
1286         notes           => <<"  NOTES");
1287         Returns an object/hash of transaction, circ, title where transaction = an open 
1288         user transactions (mbts objects), circ is the attached circluation, and title
1289         is the title the circ points to
1290         Params are login_session, user_id
1291         Optional third parameter is the transactions type.  defaults to all
1292         NOTES
1293
1294 __PACKAGE__->register_method(
1295         method  => "user_transactions",
1296         api_name        => "open-ils.actor.user.transactions.have_charge.count",
1297         notes           => <<"  NOTES");
1298         Returns an object/hash of transaction, circ, title where transaction = an open 
1299         user transactions that has an initial charge (mbts objects), circ is the 
1300         attached circluation, and title is the title the circ points to
1301         Params are login_session, user_id
1302         Optional third parameter is the transactions type.  defaults to all
1303         NOTES
1304
1305 __PACKAGE__->register_method(
1306         method  => "user_transactions",
1307         api_name        => "open-ils.actor.user.transactions.have_balance.count",
1308         notes           => <<"  NOTES");
1309         Returns an object/hash of transaction, circ, title where transaction = an open 
1310         user transaction that has a balance (mbts objects), circ is the attached 
1311         circluation, and title is the title the circ points to
1312         Params are login_session, user_id
1313         Optional third parameter is the transaction type.  defaults to all
1314         NOTES
1315
1316 __PACKAGE__->register_method(
1317         method  => "user_transactions",
1318         api_name        => "open-ils.actor.user.transactions.have_balance.total",
1319         notes           => <<"  NOTES");
1320         Returns an object/hash of transaction, circ, title where transaction = an open 
1321         user transaction that has a balance (mbts objects), circ is the attached 
1322         circluation, and title is the title the circ points to
1323         Params are login_session, user_id
1324         Optional third parameter is the transaction type.  defaults to all
1325         NOTES
1326
1327
1328
1329 sub user_transactions {
1330         my( $self, $client, $login_session, $user_id, $type ) = @_;
1331
1332         my( $user_obj, $target, $evt ) = $apputils->checkses_requestor(
1333                 $login_session, $user_id, 'VIEW_USER_TRANSACTIONS' );
1334         return $evt if $evt;
1335
1336         my $api = $self->api_name();
1337         my $trans;
1338         my @xact;
1339
1340         if(defined($type)) { @xact = (xact_type =>  $type); 
1341
1342         } else { @xact = (); }
1343
1344         ($trans) = $self
1345                 ->method_lookup('open-ils.actor.user.transactions.history.still_open')
1346                 ->run($login_session => $user_id => $type);
1347
1348         if($api =~ /have_charge/o) {
1349
1350                 $trans = [ grep { int($_->total_owed * 100) > 0 } @$trans ];
1351
1352         } elsif($api =~ /have_balance/o) {
1353
1354                 $trans = [ grep { int($_->balance_owed * 100) != 0 } @$trans ];
1355         } else {
1356
1357                 $trans = [ grep { int($_->total_owed * 100) > 0 } @$trans ];
1358
1359         }
1360
1361         if($api =~ /total/o) { 
1362                 my $total = 0.0;
1363                 for my $t (@$trans) {
1364                         $total += $t->balance_owed;
1365                 }
1366
1367                 $logger->debug("Total balance owed by user $user_id: $total");
1368                 return $total;
1369         }
1370
1371         if($api =~ /count/o) { return scalar @$trans; }
1372         if($api !~ /fleshed/o) { return $trans; }
1373
1374         my @resp;
1375         for my $t (@$trans) {
1376                         
1377                 if( $t->xact_type ne 'circulation' ) {
1378                         push @resp, {transaction => $t};
1379                         next;
1380                 }
1381
1382                 my $circ = $apputils->simple_scalar_request(
1383                                 "open-ils.cstore",
1384                                 "open-ils.cstore.direct.action.circulation.retrieve",
1385                                 $t->id );
1386
1387                 next unless $circ;
1388
1389                 my $title = $apputils->simple_scalar_request(
1390                         "open-ils.storage", 
1391                         "open-ils.storage.fleshed.biblio.record_entry.retrieve_by_copy",
1392                         $circ->target_copy );
1393
1394                 next unless $title;
1395
1396                 my $u = OpenILS::Utils::ModsParser->new();
1397                 $u->start_mods_batch($title->marc());
1398                 my $mods = $u->finish_mods_batch();
1399                 $mods->doc_id($title->id) if $mods;
1400
1401                 push @resp, {transaction => $t, circ => $circ, record => $mods };
1402
1403         }
1404
1405         return \@resp; 
1406
1407
1408
1409 __PACKAGE__->register_method(
1410         method  => "user_transaction_retrieve",
1411         api_name        => "open-ils.actor.user.transaction.fleshed.retrieve",
1412         argc            => 1,
1413         notes           => <<"  NOTES");
1414         Returns a fleshedtransaction record
1415         NOTES
1416 __PACKAGE__->register_method(
1417         method  => "user_transaction_retrieve",
1418         api_name        => "open-ils.actor.user.transaction.retrieve",
1419         argc            => 1,
1420         notes           => <<"  NOTES");
1421         Returns a transaction record
1422         NOTES
1423 sub user_transaction_retrieve {
1424         my( $self, $client, $login_session, $bill_id ) = @_;
1425
1426         my $trans = $apputils->simple_scalar_request( 
1427                 "open-ils.cstore",
1428                 "open-ils.cstore.direct.money.billable_transaction_summary.retrieve",
1429                 $bill_id
1430         );
1431
1432         my( $user_obj, $target, $evt ) = $apputils->checkses_requestor(
1433                 $login_session, $trans->usr, 'VIEW_USER_TRANSACTIONS' );
1434         return $evt if $evt;
1435         
1436         my $api = $self->api_name();
1437         if($api !~ /fleshed/o) { return $trans; }
1438
1439         if( $trans->xact_type ne 'circulation' ) {
1440                 $logger->debug("Returning non-circ transaction");
1441                 return {transaction => $trans};
1442         }
1443
1444         my $circ = $apputils->simple_scalar_request(
1445                         "open-ils.cstore",
1446                         "open-ils..direct.action.circulation.retrieve",
1447                         $trans->id );
1448
1449         return {transaction => $trans} unless $circ;
1450         $logger->debug("Found the circ transaction");
1451
1452         my $title = $apputils->simple_scalar_request(
1453                 "open-ils.storage", 
1454                 "open-ils.storage.fleshed.biblio.record_entry.retrieve_by_copy",
1455                 $circ->target_copy );
1456
1457         return {transaction => $trans, circ => $circ } unless $title;
1458         $logger->debug("Found the circ title");
1459
1460         my $mods;
1461         try {
1462                 my $u = OpenILS::Utils::ModsParser->new();
1463                 $u->start_mods_batch($title->marc());
1464                 $mods = $u->finish_mods_batch();
1465         } otherwise {
1466                 if ($title->id == OILS_PRECAT_RECORD) {
1467                         my $copy = $apputils->simple_scalar_request(
1468                                 "open-ils.cstore",
1469                                 "open-ils.cstore.direct.asset.copy.retrieve",
1470                                 $circ->target_copy );
1471
1472                         $mods = new Fieldmapper::metabib::virtual_record;
1473                         $mods->doc_id(OILS_PRECAT_RECORD);
1474                         $mods->title($copy->dummy_title);
1475                         $mods->author($copy->dummy_author);
1476                 }
1477         };
1478
1479         $logger->debug("MODSized the circ title");
1480
1481         return {transaction => $trans, circ => $circ, record => $mods };
1482 }
1483
1484
1485 __PACKAGE__->register_method(
1486         method  => "hold_request_count",
1487         api_name        => "open-ils.actor.user.hold_requests.count",
1488         argc            => 1,
1489         notes           => <<"  NOTES");
1490         Returns hold ready/total counts
1491         NOTES
1492 sub hold_request_count {
1493         my( $self, $client, $login_session, $userid ) = @_;
1494
1495         my( $user_obj, $target, $evt ) = $apputils->checkses_requestor(
1496                 $login_session, $userid, 'VIEW_HOLD' );
1497         return $evt if $evt;
1498         
1499
1500         my $holds = $apputils->simple_scalar_request(
1501                         "open-ils.cstore",
1502                         "open-ils.cstore.direct.action.hold_request.search.atomic",
1503                         { 
1504                                 usr => $userid,
1505                                 fulfillment_time => {"=" => undef },
1506                                 cancel_time => undef,
1507                         }
1508         );
1509
1510         my @ready;
1511         for my $h (@$holds) {
1512                 next unless $h->capture_time and $h->current_copy;
1513
1514                 my $copy = $apputils->simple_scalar_request(
1515                         "open-ils.cstore",
1516                         "open-ils.cstore.direct.asset.copy.retrieve",
1517                         $h->current_copy
1518                 );
1519
1520                 if ($copy and $copy->status == 8) {
1521                         push @ready, $h;
1522                 }
1523         }
1524
1525         return { total => scalar(@$holds), ready => scalar(@ready) };
1526 }
1527
1528
1529 __PACKAGE__->register_method(
1530         method  => "checkedout_count",
1531         api_name        => "open-ils.actor.user.checked_out.count__",
1532         argc            => 1,
1533         notes           => <<"  NOTES");
1534         Returns a transaction record
1535         NOTES
1536
1537 # XXX Deprecate Me
1538 sub checkedout_count {
1539         my( $self, $client, $login_session, $userid ) = @_;
1540
1541         my( $user_obj, $target, $evt ) = $apputils->checkses_requestor(
1542                 $login_session, $userid, 'VIEW_CIRCULATIONS' );
1543         return $evt if $evt;
1544         
1545         my $circs = $apputils->simple_scalar_request(
1546                         "open-ils.cstore",
1547                         "open-ils.cstore.direct.action.circulation.search.atomic",
1548                         { usr => $userid, stop_fines => undef }
1549                         #{ usr => $userid, checkin_time => {"=" => undef } }
1550         );
1551
1552         my $parser = DateTime::Format::ISO8601->new;
1553
1554         my (@out,@overdue);
1555         for my $c (@$circs) {
1556                 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
1557                 my $due = $due_dt->epoch;
1558
1559                 if ($due < DateTime->today->epoch) {
1560                         push @overdue, $c;
1561                 }
1562         }
1563
1564         return { total => scalar(@$circs), overdue => scalar(@overdue) };
1565 }
1566
1567
1568 __PACKAGE__->register_method(
1569         method          => "checked_out",
1570         api_name                => "open-ils.actor.user.checked_out",
1571         argc                    => 2,
1572         signature       => q/
1573                 Returns a structure of circulations objects sorted by
1574                 out, overdue, lost, claims_returned, long_overdue.
1575                 A list of IDs are returned of each type.
1576                 lost, long_overdue, and claims_returned circ will not
1577                 be "finished" (there is an outstanding balance or some 
1578                 other pending action on the circ). 
1579
1580                 The .count method also includes a 'total' field which 
1581                 sums all "open" circs
1582         /
1583 );
1584
1585 __PACKAGE__->register_method(
1586         method          => "checked_out",
1587         api_name                => "open-ils.actor.user.checked_out.count",
1588         argc                    => 2,
1589         signature       => q/@see open-ils.actor.user.checked_out/
1590 );
1591
1592 sub checked_out {
1593         my( $self, $conn, $auth, $userid ) = @_;
1594
1595         my $e = new_editor(authtoken=>$auth);
1596         return $e->event unless $e->checkauth;
1597
1598         if( $userid ne $e->requestor->id ) {
1599                 return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1600         }
1601
1602         my $count = $self->api_name =~ /count/;
1603         return _checked_out( $count, $e, $userid );
1604 }
1605
1606 sub _checked_out {
1607         my( $iscount, $e, $userid ) = @_;
1608
1609         my $circs = $e->search_action_circulation( 
1610                 { usr => $userid, stop_fines => undef });
1611
1612         my $mcircs = $e->search_action_circulation( 
1613                 { 
1614                         usr => $userid, 
1615                         checkin_time => undef, 
1616                         xact_finish => undef, 
1617                         stop_fines => OILS_STOP_FINES_MAX_FINES 
1618                 });
1619
1620         
1621         push( @$circs, @$mcircs );
1622
1623         my $parser = DateTime::Format::ISO8601->new;
1624
1625         # split the circs up into overdue and not-overdue circs
1626         my (@out,@overdue);
1627         for my $c (@$circs) {
1628                 if( $c->due_date ) {
1629                         my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
1630                         my $due = $due_dt->epoch;
1631                         if ($due < DateTime->today->epoch) {
1632                                 push @overdue, $c->id;
1633                         } else {
1634                                 push @out, $c->id;
1635                         }
1636                 } else {
1637                         push @out, $c->id;
1638                 }
1639         }
1640
1641         # grab all of the lost, claims-returned, and longoverdue circs
1642         #my $open = $e->search_action_circulation(
1643         #       {usr => $userid, stop_fines => { '!=' => undef }, xact_finish => undef });
1644
1645
1646         # these items have stop_fines, but no xact_finish, so money
1647         # is owed on them and they have not been checked in
1648         my $open = $e->search_action_circulation(
1649                 {
1650                         usr                             => $userid, 
1651                         stop_fines              => { '!=' => undef }, 
1652                         xact_finish             => undef,
1653                         checkin_time    => undef,
1654                 }
1655         );
1656
1657
1658         my( @lost, @cr, @lo );
1659         for my $c (@$open) {
1660                 push( @lost, $c->id ) if $c->stop_fines eq 'LOST';
1661                 push( @cr, $c->id ) if $c->stop_fines eq 'CLAIMSRETURNED';
1662                 push( @lo, $c->id ) if $c->stop_fines eq 'LONGOVERDUE';
1663         }
1664
1665
1666         if( $iscount ) {
1667                 return {
1668                         total           => @$circs + @lost + @cr + @lo,
1669                         out             => scalar(@out),
1670                         overdue => scalar(@overdue),
1671                         lost            => scalar(@lost),
1672                         claims_returned => scalar(@cr),
1673                         long_overdue            => scalar(@lo)
1674                 };
1675         }
1676
1677         return {
1678                 out             => \@out,
1679                 overdue => \@overdue,
1680                 lost            => \@lost,
1681                 claims_returned => \@cr,
1682                 long_overdue            => \@lo
1683         };
1684 }
1685
1686
1687
1688 __PACKAGE__->register_method(
1689         method          => "checked_in_with_fines",
1690         api_name                => "open-ils.actor.user.checked_in_with_fines",
1691         argc                    => 2,
1692         signature       => q/@see open-ils.actor.user.checked_out/
1693 );
1694 sub checked_in_with_fines {
1695         my( $self, $conn, $auth, $userid ) = @_;
1696
1697         my $e = new_editor(authtoken=>$auth);
1698         return $e->event unless $e->checkauth;
1699
1700         if( $userid ne $e->requestor->id ) {
1701                 return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1702         }
1703
1704         # money is owed on these items and they are checked in
1705         my $open = $e->search_action_circulation(
1706                 {
1707                         usr                             => $userid, 
1708                         xact_finish             => undef,
1709                         checkin_time    => { "!=" => undef },
1710                 }
1711         );
1712
1713
1714         my( @lost, @cr, @lo );
1715         for my $c (@$open) {
1716                 push( @lost, $c->id ) if $c->stop_fines eq 'LOST';
1717                 push( @cr, $c->id ) if $c->stop_fines eq 'CLAIMSRETURNED';
1718                 push( @lo, $c->id ) if $c->stop_fines eq 'LONGOVERDUE';
1719         }
1720
1721         return {
1722                 lost            => \@lost,
1723                 claims_returned => \@cr,
1724                 long_overdue            => \@lo
1725         };
1726 }
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736 __PACKAGE__->register_method(
1737         method  => "user_transaction_history",
1738         api_name        => "open-ils.actor.user.transactions.history",
1739         argc            => 1,
1740         notes           => <<"  NOTES");
1741         Returns a list of billable transaction ids for a user, optionally by type
1742         NOTES
1743 __PACKAGE__->register_method(
1744         method  => "user_transaction_history",
1745         api_name        => "open-ils.actor.user.transactions.history.have_charge",
1746         argc            => 1,
1747         notes           => <<"  NOTES");
1748         Returns a list of billable transaction ids for a user that have an initial charge, optionally by type
1749         NOTES
1750 __PACKAGE__->register_method(
1751         method  => "user_transaction_history",
1752         api_name        => "open-ils.actor.user.transactions.history.have_balance",
1753         argc            => 1,
1754         notes           => <<"  NOTES");
1755         Returns a list of billable transaction ids for a user that have a balance, optionally by type
1756         NOTES
1757 __PACKAGE__->register_method(
1758         method  => "user_transaction_history",
1759         api_name        => "open-ils.actor.user.transactions.history.still_open",
1760         argc            => 1,
1761         notes           => <<"  NOTES");
1762         Returns a list of billable transaction ids for a user that are not finished
1763         NOTES
1764 __PACKAGE__->register_method(
1765         method  => "user_transaction_history",
1766         api_name        => "open-ils.actor.user.transactions.history.have_bill",
1767         argc            => 1,
1768         notes           => <<"  NOTES");
1769         Returns a list of billable transaction ids for a user that has billings
1770         NOTES
1771
1772
1773
1774 =head old
1775 sub _user_transaction_history {
1776         my( $self, $client, $login_session, $user_id, $type ) = @_;
1777
1778         my( $user_obj, $target, $evt ) = $apputils->checkses_requestor(
1779                 $login_session, $user_id, 'VIEW_USER_TRANSACTIONS' );
1780         return $evt if $evt;
1781
1782         my $api = $self->api_name();
1783         my @xact;
1784         my @charge;
1785         my @balance;
1786
1787         @xact = (xact_type =>  $type) if(defined($type));
1788         @balance = (balance_owed => { "!=" => 0}) if($api =~ /have_balance/);
1789         @charge  = (last_billing_ts => { "<>" => undef }) if $api =~ /have_charge/;
1790
1791         $logger->debug("searching for transaction history: @xact : @balance, @charge");
1792
1793         my $trans = $apputils->simple_scalar_request( 
1794                 "open-ils.cstore",
1795                 "open-ils.cstore.direct.money.billable_transaction_summary.search.atomic",
1796                 { usr => $user_id, @xact, @charge, @balance }, { order_by => { mbts => 'xact_start DESC' } });
1797
1798         return [ map { $_->id } @$trans ];
1799 }
1800 =cut
1801
1802 sub _make_mbts {
1803         my @xacts = @_;
1804
1805         my @mbts;
1806         for my $x (@xacts) {
1807                 my $s = new Fieldmapper::money::billable_transaction_summary;
1808                 $s->id( $x->id );
1809                 $s->usr( $x->usr );
1810                 $s->xact_start( $x->xact_start );
1811                 $s->xact_finish( $x->xact_finish );
1812
1813                 my $to = 0.0;
1814                 my $lb = undef;
1815                 for my $b (@{ $x->billings }) {
1816                         next if ($U->is_true($b->voided));
1817                         $to += $b->amount;
1818                         $lb ||= $b->billing_ts;
1819                         if ($b->billing_ts ge $lb) {
1820                                 $lb = $b->billing_ts;
1821                                 $s->last_billing_note($b->note);
1822                                 $s->last_billing_ts($b->billing_ts);
1823                                 $s->last_billing_type($b->billing_type);
1824                         }
1825                 }
1826                 $s->total_owed( $to );
1827
1828                 my $tp = 0.0;
1829                 my $lp = undef;
1830                 for my $p (@{ $x->payments }) {
1831                         next if ($U->is_true($p->voided));
1832                         $tp += $p->amount;
1833                         $lp ||= $p->payment_ts;
1834                         if ($p->payment_ts ge $lp) {
1835                                 $lp = $p->payment_ts;
1836                                 $s->last_payment_note($p->note);
1837                                 $s->last_payment_ts($p->payment_ts);
1838                                 $s->last_payment_type($p->payment_type);
1839                         }
1840                 }
1841                 $s->total_paid( $tp );
1842
1843                 $s->balance_owed( $s->total_owed - $s->total_paid );
1844
1845                 $s->xact_type( 'grocery' ) if ($x->grocery);
1846                 $s->xact_type( 'circulation' ) if ($x->circulation);
1847
1848                 push @mbts, $s;
1849         }
1850
1851         return @mbts;
1852 }
1853
1854 sub user_transaction_history {
1855         my( $self, $conn, $auth, $userid, $type ) = @_;
1856         my $e = new_editor(authtoken=>$auth);
1857         return $e->event unless $e->checkauth;
1858         return $e->event unless $e->allowed('VIEW_USER_TRANSACTIONS');
1859
1860         my $api = $self->api_name;
1861         my @xact_finish  = (xact_finish => undef ) if $api =~ /still_open/;
1862
1863         my @xacts = @{ $e->search_money_billable_transaction(
1864                 [       { usr => $userid, @xact_finish },
1865                         { flesh => 1,
1866                           flesh_fields => { mbt => [ qw/billings payments grocery circulation/ ] },
1867                           order_by => { mbt => 'xact_start DESC' },
1868                         }
1869                 ]
1870         ) };
1871
1872         my @mbts = _make_mbts( @xacts );
1873
1874         if(defined($type)) {
1875                 @mbts = grep { $_->xact_type eq $type } @mbts;
1876         }
1877
1878         if($api =~ /have_balance/o) {
1879                 @mbts = grep { int($_->balance_owed * 100) != 0 } @mbts;
1880         }
1881
1882         if($api =~ /have_charge/o) {
1883                 @mbts = grep { defined($_->last_billing_ts) } @mbts;
1884         }
1885
1886         if($api =~ /have_bill/o) {
1887                 @mbts = grep { int($_->total_owed * 100) != 0 } @mbts;
1888         }
1889
1890         return [@mbts];
1891 }
1892
1893
1894
1895 __PACKAGE__->register_method(
1896         method  => "user_perms",
1897         api_name        => "open-ils.actor.permissions.user_perms.retrieve",
1898         argc            => 1,
1899         notes           => <<"  NOTES");
1900         Returns a list of permissions
1901         NOTES
1902 sub user_perms {
1903         my( $self, $client, $authtoken, $user ) = @_;
1904
1905         my( $staff, $evt ) = $apputils->checkses($authtoken);
1906         return $evt if $evt;
1907
1908         $user ||= $staff->id;
1909
1910         if( $user != $staff->id and $evt = $apputils->check_perms( $staff->id, $staff->home_ou, 'VIEW_PERMISSION') ) {
1911                 return $evt;
1912         }
1913
1914         return $apputils->simple_scalar_request(
1915                 "open-ils.storage",
1916                 "open-ils.storage.permission.user_perms.atomic",
1917                 $user);
1918 }
1919
1920 __PACKAGE__->register_method(
1921         method  => "retrieve_perms",
1922         api_name        => "open-ils.actor.permissions.retrieve",
1923         notes           => <<"  NOTES");
1924         Returns a list of permissions
1925         NOTES
1926 sub retrieve_perms {
1927         my( $self, $client ) = @_;
1928         return $apputils->simple_scalar_request(
1929                 "open-ils.cstore",
1930                 "open-ils.cstore.direct.permission.perm_list.search.atomic",
1931                 { id => { '!=' => undef } }
1932         );
1933 }
1934
1935 __PACKAGE__->register_method(
1936         method  => "retrieve_groups",
1937         api_name        => "open-ils.actor.groups.retrieve",
1938         notes           => <<"  NOTES");
1939         Returns a list of user groupss
1940         NOTES
1941 sub retrieve_groups {
1942         my( $self, $client ) = @_;
1943         return new_editor()->retrieve_all_permission_grp_tree();
1944 }
1945
1946 __PACKAGE__->register_method(
1947         method  => "retrieve_org_address",
1948         api_name        => "open-ils.actor.org_unit.address.retrieve",
1949         notes           => <<'  NOTES');
1950         Returns an org_unit address by ID
1951         @param An org_address ID
1952         NOTES
1953 sub retrieve_org_address {
1954         my( $self, $client, $id ) = @_;
1955         return $apputils->simple_scalar_request(
1956                 "open-ils.cstore",
1957                 "open-ils.cstore.direct.actor.org_address.retrieve",
1958                 $id
1959         );
1960 }
1961
1962 __PACKAGE__->register_method(
1963         method  => "retrieve_groups_tree",
1964         api_name        => "open-ils.actor.groups.tree.retrieve",
1965         notes           => <<"  NOTES");
1966         Returns a list of user groups
1967         NOTES
1968 sub retrieve_groups_tree {
1969         my( $self, $client ) = @_;
1970         return new_editor()->search_permission_grp_tree(
1971                 [
1972                         { parent => undef},
1973                         {       
1974                                 flesh                           => 10, 
1975                                 flesh_fields    => { pgt => ["children"] }, 
1976                                 order_by                        => { pgt => 'name'}
1977                         }
1978                 ]
1979         )->[0];
1980 }
1981
1982
1983 # turns an org list into an org tree
1984 =head old code
1985 sub build_group_tree {
1986
1987         my( $self, $grplist) = @_;
1988
1989         return $grplist unless ( 
1990                         ref($grplist) and @$grplist > 1 );
1991
1992         my @list = sort { $a->name cmp $b->name } @$grplist;
1993
1994         my $root;
1995         for my $grp (@list) {
1996
1997                 if ($grp and !defined($grp->parent)) {
1998                         $root = $grp;
1999                         next;
2000                 }
2001                 my ($parent) = grep { $_->id == $grp->parent} @list;
2002
2003                 $parent->children([]) unless defined($parent->children); 
2004                 push( @{$parent->children}, $grp );
2005         }
2006
2007         return $root;
2008 }
2009 =cut
2010
2011
2012 __PACKAGE__->register_method(
2013         method  => "add_user_to_groups",
2014         api_name        => "open-ils.actor.user.set_groups",
2015         notes           => <<"  NOTES");
2016         Adds a user to one or more permission groups
2017         NOTES
2018
2019 sub add_user_to_groups {
2020         my( $self, $client, $authtoken, $userid, $groups ) = @_;
2021
2022         my( $requestor, $target, $evt ) = $apputils->checkses_requestor(
2023                 $authtoken, $userid, 'CREATE_USER_GROUP_LINK' );
2024         return $evt if $evt;
2025
2026         ( $requestor, $target, $evt ) = $apputils->checkses_requestor(
2027                 $authtoken, $userid, 'REMOVE_USER_GROUP_LINK' );
2028         return $evt if $evt;
2029
2030         $apputils->simplereq(
2031                 'open-ils.storage',
2032                 'open-ils.storage.direct.permission.usr_grp_map.mass_delete', { usr => $userid } );
2033                 
2034         for my $group (@$groups) {
2035                 my $link = Fieldmapper::permission::usr_grp_map->new;
2036                 $link->grp($group);
2037                 $link->usr($userid);
2038
2039                 my $id = $apputils->simplereq(
2040                         'open-ils.storage',
2041                         'open-ils.storage.direct.permission.usr_grp_map.create', $link );
2042         }
2043
2044         return 1;
2045 }
2046
2047 __PACKAGE__->register_method(
2048         method  => "get_user_perm_groups",
2049         api_name        => "open-ils.actor.user.get_groups",
2050         notes           => <<"  NOTES");
2051         Retrieve a user's permission groups.
2052         NOTES
2053
2054
2055 sub get_user_perm_groups {
2056         my( $self, $client, $authtoken, $userid ) = @_;
2057
2058         my( $requestor, $target, $evt ) = $apputils->checkses_requestor(
2059                 $authtoken, $userid, 'VIEW_PERM_GROUPS' );
2060         return $evt if $evt;
2061
2062         return $apputils->simplereq(
2063                 'open-ils.cstore',
2064                 'open-ils.cstore.direct.permission.usr_grp_map.search.atomic', { usr => $userid } );
2065 }       
2066
2067
2068
2069 __PACKAGE__->register_method (
2070         method          => 'register_workstation',
2071         api_name                => 'open-ils.actor.workstation.register.override',
2072         signature       => q/@see open-ils.actor.workstation.register/);
2073
2074 __PACKAGE__->register_method (
2075         method          => 'register_workstation',
2076         api_name                => 'open-ils.actor.workstation.register',
2077         signature       => q/
2078                 Registers a new workstion in the system
2079                 @param authtoken The login session key
2080                 @param name The name of the workstation id
2081                 @param owner The org unit that owns this workstation
2082                 @return The workstation id on success, WORKSTATION_NAME_EXISTS
2083                 if the name is already in use.
2084         /);
2085
2086 sub _register_workstation {
2087         my( $self, $connection, $authtoken, $name, $owner ) = @_;
2088         my( $requestor, $evt ) = $U->checkses($authtoken);
2089         return $evt if $evt;
2090         $evt = $U->check_perms($requestor->id, $owner, 'REGISTER_WORKSTATION');
2091         return $evt if $evt;
2092
2093         my $ws = $U->cstorereq(
2094                 'open-ils.cstore.direct.actor.workstation.search', { name => $name } );
2095         return OpenILS::Event->new('WORKSTATION_NAME_EXISTS') if $ws;
2096
2097         $ws = Fieldmapper::actor::workstation->new;
2098         $ws->owning_lib($owner);
2099         $ws->name($name);
2100
2101         my $id = $U->storagereq(
2102                 'open-ils.storage.direct.actor.workstation.create', $ws );
2103         return $U->DB_UPDATE_FAILED($ws) unless $id;
2104
2105         $ws->id($id);
2106         return $ws->id();
2107 }
2108
2109 sub register_workstation {
2110         my( $self, $conn, $authtoken, $name, $owner ) = @_;
2111
2112         my $e = new_editor(authtoken=>$authtoken, xact=>1);
2113         return $e->event unless $e->checkauth;
2114         return $e->event unless $e->allowed('REGISTER_WORKSTATION'); # XXX rely on editor perms
2115         my $existing = $e->search_actor_workstation({name => $name});
2116
2117         if( @$existing ) {
2118                 if( $self->api_name =~ /override/o ) {
2119                         return $e->event unless $e->allowed('DELETE_WORKSTATION'); # XXX rely on editor perms
2120                         return $e->event unless $e->delete_actor_workstation($$existing[0]);
2121                 } else {
2122                         return OpenILS::Event->new('WORKSTATION_NAME_EXISTS')
2123                 }
2124         }
2125
2126         my $ws = Fieldmapper::actor::workstation->new;
2127         $ws->owning_lib($owner);
2128         $ws->name($name);
2129         $e->create_actor_workstation($ws) or return $e->event;
2130         $e->commit;
2131         return $ws->id; # note: editor sets the id on the new object for us
2132 }
2133
2134
2135 __PACKAGE__->register_method (
2136         method          => 'fetch_patron_note',
2137         api_name                => 'open-ils.actor.note.retrieve.all',
2138         signature       => q/
2139                 Returns a list of notes for a given user
2140                 Requestor must have VIEW_USER permission if pub==false and
2141                 @param authtoken The login session key
2142                 @param args Hash of params including
2143                         patronid : the patron's id
2144                         pub : true if retrieving only public notes
2145         /
2146 );
2147
2148 sub fetch_patron_note {
2149         my( $self, $conn, $authtoken, $args ) = @_;
2150         my $patronid = $$args{patronid};
2151
2152         my($reqr, $evt) = $U->checkses($authtoken);
2153
2154         my $patron;
2155         ($patron, $evt) = $U->fetch_user($patronid);
2156         return $evt if $evt;
2157
2158         if($$args{pub}) {
2159                 if( $patronid ne $reqr->id ) {
2160                         $evt = $U->check_perms($reqr->id, $patron->home_ou, 'VIEW_USER');
2161                         return $evt if $evt;
2162                 }
2163                 return $U->cstorereq(
2164                         'open-ils.cstore.direct.actor.usr_note.search.atomic', 
2165                         { usr => $patronid, pub => 't' } );
2166         }
2167
2168         $evt = $U->check_perms($reqr->id, $patron->home_ou, 'VIEW_USER');
2169         return $evt if $evt;
2170
2171         return $U->cstorereq(
2172                 'open-ils.cstore.direct.actor.usr_note.search.atomic', { usr => $patronid } );
2173 }
2174
2175 __PACKAGE__->register_method (
2176         method          => 'create_user_note',
2177         api_name                => 'open-ils.actor.note.create',
2178         signature       => q/
2179                 Creates a new note for the given user
2180                 @param authtoken The login session key
2181                 @param note The note object
2182         /
2183 );
2184 sub create_user_note {
2185         my( $self, $conn, $authtoken, $note ) = @_;
2186         my( $reqr, $patron, $evt ) = 
2187                 $U->checkses_requestor($authtoken, $note->usr, 'UPDATE_USER');
2188         return $evt if $evt;
2189         $logger->activity("user ".$reqr->id." creating note for user ".$note->usr);
2190
2191         $note->creator($reqr->id);
2192         my $id = $U->storagereq(
2193                 'open-ils.storage.direct.actor.usr_note.create', $note );
2194         return $U->DB_UPDATE_FAILED($note) unless $id;
2195         return $id;
2196 }
2197
2198
2199 __PACKAGE__->register_method (
2200         method          => 'delete_user_note',
2201         api_name                => 'open-ils.actor.note.delete',
2202         signature       => q/
2203                 Deletes a note for the given user
2204                 @param authtoken The login session key
2205                 @param noteid The note id
2206         /
2207 );
2208 sub delete_user_note {
2209         my( $self, $conn, $authtoken, $noteid ) = @_;
2210
2211         my $note = $U->cstorereq(
2212                 'open-ils.cstore.direct.actor.usr_note.retrieve', $noteid);
2213         return OpenILS::Event->new('ACTOR_USER_NOTE_NOT_FOUND') unless $note;
2214
2215         my( $reqr, $patron, $evt ) = 
2216                 $U->checkses_requestor($authtoken, $note->usr, 'UPDATE_USER');
2217         return $evt if $evt;
2218         $logger->activity("user ".$reqr->id." deleting note [$noteid] for user ".$note->usr);
2219
2220         my $stat = $U->storagereq(
2221                 'open-ils.storage.direct.actor.usr_note.delete', $noteid );
2222         return $U->DB_UPDATE_FAILED($note) unless defined $stat;
2223         return $stat;
2224 }
2225
2226
2227 __PACKAGE__->register_method (
2228         method          => 'update_user_note',
2229         api_name                => 'open-ils.actor.note.update',
2230         signature       => q/
2231                 @param authtoken The login session key
2232                 @param note The note
2233         /
2234 );
2235
2236 sub update_user_note {
2237         my( $self, $conn, $auth, $note ) = @_;
2238         my $e = new_editor(authtoken=>$auth, xact=>1);
2239         return $e->event unless $e->checkauth;
2240         my $patron = $e->retrieve_actor_user($note->usr)
2241                 or return $e->event;
2242         return $e->event unless 
2243                 $e->allowed('UPDATE_USER', $patron->home_ou);
2244         $e->update_actor_user_note($note)
2245                 or return $e->event;
2246         $e->commit;
2247         return 1;
2248 }
2249
2250
2251
2252
2253 __PACKAGE__->register_method (
2254         method          => 'create_closed_date',
2255         api_name        => 'open-ils.actor.org_unit.closed_date.create',
2256         signature       => q/
2257                 Creates a new closing entry for the given org_unit
2258                 @param authtoken The login session key
2259                 @param note The closed_date object
2260         /
2261 );
2262 sub create_closed_date {
2263         my( $self, $conn, $authtoken, $cd ) = @_;
2264
2265         my( $user, $evt ) = $U->checkses($authtoken);
2266         return $evt if $evt;
2267
2268         $evt = $U->check_perms($user->id, $cd->org_unit, 'CREATE_CLOSEING');
2269         return $evt if $evt;
2270
2271         $logger->activity("user ".$user->id." creating library closing for ".$cd->org_unit);
2272
2273         my $id = $U->storagereq(
2274                 'open-ils.storage.direct.actor.org_unit.closed_date.create', $cd );
2275         return $U->DB_UPDATE_FAILED($cd) unless $id;
2276         return $id;
2277 }
2278
2279
2280 __PACKAGE__->register_method (
2281         method          => 'delete_closed_date',
2282         api_name        => 'open-ils.actor.org_unit.closed_date.delete',
2283         signature       => q/
2284                 Deletes a closing entry for the given org_unit
2285                 @param authtoken The login session key
2286                 @param noteid The close_date id
2287         /
2288 );
2289 sub delete_closed_date {
2290         my( $self, $conn, $authtoken, $cd ) = @_;
2291
2292         my( $user, $evt ) = $U->checkses($authtoken);
2293         return $evt if $evt;
2294
2295         my $cd_obj;
2296         ($cd_obj, $evt) = fetch_closed_date($cd);
2297         return $evt if $evt;
2298
2299         $evt = $U->check_perms($user->id, $cd->org_unit, 'DELETE_CLOSEING');
2300         return $evt if $evt;
2301
2302         $logger->activity("user ".$user->id." deleting library closing for ".$cd->org_unit);
2303
2304         my $stat = $U->storagereq(
2305                 'open-ils.storage.direct.actor.org_unit.closed_date.delete', $cd );
2306         return $U->DB_UPDATE_FAILED($cd) unless $stat;
2307         return $stat;
2308 }
2309
2310
2311 __PACKAGE__->register_method(
2312         method => 'usrname_exists',
2313         api_name        => 'open-ils.actor.username.exists',
2314         signature => q/
2315                 Returns 1 if the requested username exists, returns 0 otherwise
2316         /
2317 );
2318
2319 sub usrname_exists {
2320         my( $self, $conn, $auth, $usrname ) = @_;
2321         my $e = new_editor(authtoken=>$auth);
2322         return $e->event unless $e->checkauth;
2323         my $a = $e->search_actor_user({usrname => $usrname, deleted=>'f'}, {idlist=>1});
2324         return $$a[0] if $a and @$a;
2325         return 0;
2326 }
2327
2328 __PACKAGE__->register_method(
2329         method => 'barcode_exists',
2330         api_name        => 'open-ils.actor.barcode.exists',
2331         signature => q/
2332                 Returns 1 if the requested barcode exists, returns 0 otherwise
2333         /
2334 );
2335
2336 sub barcode_exists {
2337         my( $self, $conn, $auth, $barcode ) = @_;
2338         my $e = new_editor(authtoken=>$auth);
2339         return $e->event unless $e->checkauth;
2340         my $a = $e->search_actor_card({barcode => $barcode}, {idlist=>1});
2341         return $$a[0] if $a and @$a;
2342         return 0;
2343 }
2344
2345
2346 __PACKAGE__->register_method(
2347         method => 'retrieve_net_levels',
2348         api_name        => 'open-ils.actor.net_access_level.retrieve.all',
2349 );
2350
2351 sub retrieve_net_levels {
2352         my( $self, $conn, $auth ) = @_;
2353         my $e = new_editor(authtoken=>$auth);
2354         return $e->event unless $e->checkauth;
2355         return $e->retrieve_all_config_net_access_level();
2356 }
2357
2358
2359 __PACKAGE__->register_method(
2360         method => 'fetch_org_by_shortname',
2361         api_name => 'open-ils.actor.org_unit.retrieve_by_shorname',
2362 );
2363 sub fetch_org_by_shortname {
2364         my( $self, $conn, $sname ) = @_;
2365         my $e = new_editor();
2366         my $org = $e->search_actor_org_unit({ shortname => uc($sname)})->[0];
2367         return $e->event unless $org;
2368         return $org;
2369 }
2370
2371
2372 __PACKAGE__->register_method(
2373         method => 'session_home_lib',
2374         api_name => 'open-ils.actor.session.home_lib',
2375 );
2376
2377 sub session_home_lib {
2378         my( $self, $conn, $auth ) = @_;
2379         my $e = new_editor(authtoken=>$auth);
2380         return undef unless $e->checkauth;
2381         my $org = $e->retrieve_actor_org_unit($e->requestor->home_ou);
2382         return $org->shortname;
2383 }
2384
2385
2386
2387 __PACKAGE__->register_method(
2388         method => 'slim_tree',
2389         api_name        => "open-ils.actor.org_tree.slim_hash.retrieve",
2390 );
2391 sub slim_tree {
2392         my $tree = new_editor()->search_actor_org_unit( 
2393                 [
2394                         {"parent_ou" => undef },
2395                         {
2396                                 flesh                           => 2,
2397                                 flesh_fields    => { aou =>  ['children'] },
2398                                 order_by                        => { aou => 'name'},
2399                                 select                  => { aou => ["id","shortname", "name"]},
2400                         }
2401                 ]
2402         )->[0];
2403
2404         return trim_tree($tree);
2405 }
2406
2407
2408 sub trim_tree {
2409         my $tree = shift;
2410         return undef unless $tree;
2411         my $htree = {
2412                 code => $tree->shortname,
2413                 name => $tree->name,
2414         };
2415         if( $tree->children and @{$tree->children} ) {
2416                 $htree->{children} = [];
2417                 for my $c (@{$tree->children}) {
2418                         push( @{$htree->{children}}, trim_tree($c) );
2419                 }
2420         }
2421
2422         return $htree;
2423 }
2424
2425
2426
2427 __PACKAGE__->register_method(
2428         method  => "user_retrieve_fleshed_by_id",
2429         api_name        => "open-ils.actor.user.fleshed.retrieve",);
2430
2431 sub user_retrieve_fleshed_by_id {
2432         my( $self, $client, $auth, $user_id, $fields ) = @_;
2433         my $e = new_editor(authtoken => $auth);
2434         return $e->event unless $e->checkauth;
2435         if( $e->requestor->id != $user_id ) {
2436                 return $e->event unless $e->allowed('VIEW_USER');
2437         }
2438         $fields ||= [
2439                 "cards",
2440                 "card",
2441                 "standing_penalties",
2442                 "addresses",
2443                 "billing_address",
2444                 "mailing_address",
2445                 "stat_cat_entries" ];
2446         return new_flesh_user($user_id, $fields, $e);
2447 }
2448
2449
2450 sub new_flesh_user {
2451
2452         my $id = shift;
2453         my $fields = shift || [];
2454         my $e   = shift || new_editor(xact=>1);
2455
2456         my $user = $e->retrieve_actor_user(
2457         [
2458         $id,
2459         {
2460                 "flesh"                         => 1,
2461                 "flesh_fields" =>  { "au" => $fields }
2462         }
2463         ]
2464         ) or return $e->event;
2465
2466
2467         if( grep { $_ eq 'addresses' } @$fields ) {
2468
2469                 $user->addresses([]) unless @{$user->addresses};
2470         
2471                 if( ref $user->billing_address ) {
2472                         unless( grep { $user->billing_address->id == $_->id } @{$user->addresses} ) {
2473                                 push( @{$user->addresses}, $user->billing_address );
2474                         }
2475                 }
2476         
2477                 if( ref $user->mailing_address ) {
2478                         unless( grep { $user->mailing_address->id == $_->id } @{$user->addresses} ) {
2479                                 push( @{$user->addresses}, $user->mailing_address );
2480                         }
2481                 }
2482         }
2483
2484         $e->disconnect;
2485         $user->clear_passwd();
2486         return $user;
2487 }
2488
2489
2490
2491
2492 __PACKAGE__->register_method(
2493         method  => "user_retrieve_parts",
2494         api_name        => "open-ils.actor.user.retrieve.parts",);
2495
2496 sub user_retrieve_parts {
2497         my( $self, $client, $auth, $user_id, $fields ) = @_;
2498         my $e = new_editor(authtoken => $auth);
2499         return $e->event unless $e->checkauth;
2500         if( $e->requestor->id != $user_id ) {
2501                 return $e->event unless $e->allowed('VIEW_USER');
2502         }
2503         my @resp;
2504         my $user = $e->retrieve_actor_user($user_id) or return $e->event;
2505         push(@resp, $user->$_()) for(@$fields);
2506         return \@resp;
2507 }
2508
2509
2510
2511
2512
2513
2514 1;
2515