]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
fleshing circ rules on circ object in copy details API call
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Circ.pm
1 package OpenILS::Application::Circ;
2 use OpenILS::Application;
3 use base qw/OpenILS::Application/;
4 use strict; use warnings;
5
6 use OpenILS::Application::Circ::Circulate;
7 use OpenILS::Application::Circ::Survey;
8 use OpenILS::Application::Circ::StatCat;
9 use OpenILS::Application::Circ::Holds;
10 use OpenILS::Application::Circ::HoldNotify;
11 use OpenILS::Application::Circ::Money;
12 use OpenILS::Application::Circ::NonCat;
13 use OpenILS::Application::Circ::CopyLocations;
14 use OpenILS::Application::Circ::CircCommon;
15
16 use DateTime;
17 use DateTime::Format::ISO8601;
18
19 use OpenILS::Application::AppUtils;
20
21 use OpenSRF::Utils qw/:datetime/;
22 use OpenSRF::AppSession;
23 use OpenILS::Utils::ModsParser;
24 use OpenILS::Event;
25 use OpenSRF::EX qw(:try);
26 use OpenSRF::Utils::Logger qw(:logger);
27 use OpenILS::Utils::Fieldmapper;
28 use OpenILS::Utils::Editor;
29 use OpenILS::Utils::CStoreEditor q/:funcs/;
30 use OpenILS::Const qw/:const/;
31 use OpenSRF::Utils::SettingsClient;
32 use OpenILS::Application::Cat::AssetCommon;
33
34 my $apputils = "OpenILS::Application::AppUtils";
35 my $U = $apputils;
36
37
38 # ------------------------------------------------------------------------
39 # Top level Circ package;
40 # ------------------------------------------------------------------------
41
42 sub initialize {
43         my $self = shift;
44         OpenILS::Application::Circ::Circulate->initialize();
45 }
46
47
48 __PACKAGE__->register_method(
49         method => 'retrieve_circ',
50         api_name        => 'open-ils.circ.retrieve',
51         signature => q/
52                 Retrieve a circ object by id
53                 @param authtoken Login session key
54                 @pararm circid The id of the circ object
55         /
56 );
57 sub retrieve_circ {
58         my( $s, $c, $a, $i ) = @_;
59         my $e = new_editor(authtoken => $a);
60         return $e->event unless $e->checkauth;
61         my $circ = $e->retrieve_action_circulation($i) or return $e->event;
62         if( $e->requestor->id ne $circ->usr ) {
63                 return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
64         }
65         return $circ;
66 }
67
68
69 __PACKAGE__->register_method(
70         method => 'fetch_circ_mods',
71         api_name => 'open-ils.circ.circ_modifier.retrieve.all');
72 sub fetch_circ_mods {
73     my($self, $conn, $args) = @_;
74     my $mods = new_editor()->retrieve_all_config_circ_modifier;
75     return [ map {$_->code} @$mods ] unless $$args{full};
76     return $mods;
77 }
78
79 __PACKAGE__->register_method(
80         method => 'fetch_bill_types',
81         api_name => 'open-ils.circ.billing_type.retrieve.all');
82 sub fetch_bill_types {
83         my $conf = OpenSRF::Utils::SettingsClient->new;
84         return $conf->config_value(
85                 'apps', 'open-ils.circ', 'app_settings', 'billing_types', 'type' );
86 }
87
88
89 __PACKAGE__->register_method(
90     method => 'ranged_billing_types',
91     api_name => 'open-ils.circ.billing_type.ranged.retrieve.all');
92
93 sub ranged_billing_types {
94     my($self, $conn, $auth, $org_id, $depth) = @_;
95     my $e = new_editor(authtoken => $auth);
96     return $e->event unless $e->checkauth;
97     return $e->event unless $e->allowed('VIEW_BILLING_TYPE', $org_id);
98     return $e->search_config_billing_type(
99         {owner => $U->get_org_full_path($org_id, $depth)});
100 }
101
102
103
104 # ------------------------------------------------------------------------
105 # Returns an array of {circ, record} hashes checked out by the user.
106 # ------------------------------------------------------------------------
107 __PACKAGE__->register_method(
108         method  => "checkouts_by_user",
109         api_name        => "open-ils.circ.actor.user.checked_out",
110         NOTES           => <<"  NOTES");
111         Returns a list of open circulations as a pile of objects.  Each object
112         contains the relevant copy, circ, and record
113         NOTES
114
115 sub checkouts_by_user {
116         my( $self, $client, $user_session, $user_id ) = @_;
117
118         my( $requestor, $target, $copy, $record, $evt );
119
120         ( $requestor, $target, $evt ) = 
121                 $apputils->checkses_requestor( $user_session, $user_id, 'VIEW_CIRCULATIONS');
122         return $evt if $evt;
123
124         my $circs = $apputils->simplereq(
125                 'open-ils.cstore',
126                 "open-ils.cstore.direct.action.open_circulation.search.atomic", 
127                 { usr => $target->id, checkin_time => undef } );
128 #               { usr => $target->id } );
129
130         my @results;
131         for my $circ (@$circs) {
132
133                 ( $copy, $evt )  = $apputils->fetch_copy($circ->target_copy);
134                 return $evt if $evt;
135
136                 $logger->debug("Retrieving record for copy " . $circ->target_copy);
137
138                 ($record, $evt) = $apputils->fetch_record_by_copy( $circ->target_copy );
139                 return $evt if $evt;
140
141                 my $mods = $apputils->record_to_mvr($record);
142
143                 push( @results, { copy => $copy, circ => $circ, record => $mods } );
144         }
145
146         return \@results;
147
148 }
149
150
151
152 __PACKAGE__->register_method(
153         method  => "checkouts_by_user_slim",
154         api_name        => "open-ils.circ.actor.user.checked_out.slim",
155         NOTES           => <<"  NOTES");
156         Returns a list of open circulation objects
157         NOTES
158
159 # DEPRECAT ME?? XXX
160 sub checkouts_by_user_slim {
161         my( $self, $client, $user_session, $user_id ) = @_;
162
163         my( $requestor, $target, $copy, $record, $evt );
164
165         ( $requestor, $target, $evt ) = 
166                 $apputils->checkses_requestor( $user_session, $user_id, 'VIEW_CIRCULATIONS');
167         return $evt if $evt;
168
169         $logger->debug( 'User ' . $requestor->id . 
170                 " retrieving checked out items for user " . $target->id );
171
172         # XXX Make the call correct..
173         return $apputils->simplereq(
174                 'open-ils.cstore',
175                 "open-ils.cstore.direct.action.open_circulation.search.atomic", 
176                 { usr => $target->id, checkin_time => undef } );
177 #               { usr => $target->id } );
178 }
179
180
181 __PACKAGE__->register_method(
182         method  => "checkouts_by_user_opac",
183         api_name        => "open-ils.circ.actor.user.checked_out.opac",);
184
185 # XXX Deprecate Me
186 sub checkouts_by_user_opac {
187         my( $self, $client, $auth, $user_id ) = @_;
188
189         my $e = OpenILS::Utils::Editor->new( authtoken => $auth );
190         return $e->event unless $e->checkauth;
191         $user_id ||= $e->requestor->id;
192         return $e->event unless 
193                 my $patron = $e->retrieve_actor_user($user_id);
194
195         my $data;
196         my $search = {usr => $user_id, stop_fines => undef};
197
198         if( $user_id ne $e->requestor->id ) {
199                 $data = $e->search_action_circulation(
200                         $search, {checkperm=>1, permorg=>$patron->home_ou})
201                         or return $e->event;
202
203         } else {
204                 $data = $e->search_action_circulation($search);
205         }
206
207         return $data;
208 }
209
210
211 __PACKAGE__->register_method(
212         method  => "title_from_transaction",
213         api_name        => "open-ils.circ.circ_transaction.find_title",
214         NOTES           => <<"  NOTES");
215         Returns a mods object for the title that is linked to from the 
216         copy from the hold that created the given transaction
217         NOTES
218
219 sub title_from_transaction {
220         my( $self, $client, $login_session, $transactionid ) = @_;
221
222         my( $user, $circ, $title, $evt );
223
224         ( $user, $evt ) = $apputils->checkses( $login_session );
225         return $evt if $evt;
226
227         ( $circ, $evt ) = $apputils->fetch_circulation($transactionid);
228         return $evt if $evt;
229         
230         ($title, $evt) = $apputils->fetch_record_by_copy($circ->target_copy);
231         return $evt if $evt;
232
233         return $apputils->record_to_mvr($title);
234 }
235
236
237
238 __PACKAGE__->register_method(
239         method  => "new_set_circ_lost",
240         api_name        => "open-ils.circ.circulation.set_lost",
241         signature       => q/
242         Sets the copy and related open circulation to lost
243                 @param auth
244                 @param args : barcode
245         /
246 );
247
248
249 # ---------------------------------------------------------------------
250 # Sets a circulation to lost.  updates copy status to lost
251 # applies copy and/or prcoessing fees depending on org settings
252 # ---------------------------------------------------------------------
253 sub new_set_circ_lost {
254     my( $self, $conn, $auth, $args ) = @_;
255
256     my $e = new_editor(authtoken=>$auth, xact=>1);
257     return $e->die_event unless $e->checkauth;
258
259     my $copy = $e->search_asset_copy({barcode=>$$args{barcode}, deleted=>'f'})->[0]
260         or return $e->die_event;
261
262     my $evt = OpenILS::Application::Cat::AssetCommon->set_item_lost($e, $copy->id);
263     return $evt if $evt;
264
265     $e->commit;
266     return 1;
267 }
268
269
270 __PACKAGE__->register_method(
271         method  => "set_circ_claims_returned",
272         api_name        => "open-ils.circ.circulation.set_claims_returned",
273         signature => {
274         desc => q/Sets the circ for a given item as claims returned
275                 If a backdate is provided, overdue fines will be voided
276                 back to the backdate/,
277         params => [
278             {desc => 'Authentication token', type => 'string'},
279             {desc => 'Arguments, including "barcode" and optional "backdate"', type => 'object'}
280         ],
281         return => {desc => q/1 on success, failure event on error, and 
282             PATRON_EXCEEDS_CLAIMS_RETURN_COUNT if the patron exceeds the 
283             configured claims return maximum/}
284     }
285 );
286
287 __PACKAGE__->register_method(
288         method  => "set_circ_claims_returned",
289         api_name        => "open-ils.circ.circulation.set_claims_returned.override",
290         signature => {
291         desc => q/This adds support for overrideing the configured max 
292                 claims returned amount. 
293                 @see open-ils.circ.circulation.set_claims_returned./,
294     }
295 );
296
297 sub set_circ_claims_returned {
298     my( $self, $conn, $auth, $args ) = @_;
299
300     my $e = new_editor(authtoken=>$auth, xact=>1);
301     return $e->die_event unless $e->checkauth;
302
303     my $barcode = $$args{barcode};
304     my $backdate = $$args{backdate};
305
306     $logger->info("marking circ for item $barcode as claims returned".
307         (($backdate) ? " with backdate $backdate" : ''));
308
309     my $copy = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'})->[0] 
310         or return $e->die_event;
311
312     my $circ = $e->search_action_circulation(
313         {checkin_time => undef, target_copy => $copy->id})->[0]
314             or return $e->die_event;
315
316     my $patron = $e->retrieve_actor_user($circ->usr);
317     my $max_count = $U->ou_ancestor_setting_value(
318         $circ->circ_lib, 'circ.max_patron_claim_return_count', $e);
319
320     # If the patron has too instances of many claims returned, 
321     # require an override to continue.  A configured max of 
322     # 0 means all attempts require an override
323     if(defined $max_count and $patron->claims_returned_count >= $max_count) {
324
325         if($self->api_name =~ /override/) {
326
327             # see if we're allowed to override
328             return $e->die_event unless 
329                 $e->allowed('SET_CIRC_CLAIMS_RETURNED.override', $circ->circ_lib);
330
331         } else {
332
333             # exit early and return the max claims return event
334             $e->rollback;
335             return OpenILS::Event->new(
336                 'PATRON_EXCEEDS_CLAIMS_RETURN_COUNT', 
337                 payload => {
338                     patron_count => $patron->claims_returned_count,
339                     max_count => $max_count
340                 }
341             );
342         }
343     }
344
345     $e->allowed('SET_CIRC_CLAIMS_RETURNED', $circ->circ_lib) 
346         or return $e->die_event;
347
348     $circ->stop_fines(OILS_STOP_FINES_CLAIMSRETURNED);
349         $circ->stop_fines_time('now') unless $circ->stop_fines_time;
350
351     if( $backdate ) {
352         # make it look like the circ stopped at the cliams returned time
353         $circ->stop_fines_time(clense_ISO8601($backdate));
354         my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ, $backdate);
355         return $evt if $evt;
356     }
357
358     $e->update_action_circulation($circ) or return $e->die_event;
359     $e->commit;
360     return 1;
361 }
362
363
364 __PACKAGE__->register_method(
365         method  => "post_checkin_backdate_circ",
366         api_name        => "open-ils.circ.post_checkin_backdate",
367         signature => {
368         desc => q/Back-date an already checked in circulation/,
369         params => [
370             {desc => 'Authentication token', type => 'string'},
371             {desc => 'Circ ID', type => 'number'},
372             {desc => 'ISO8601 backdate', type => 'string'},
373         ],
374         return => {desc => q/1 on success, failure event on error/}
375     }
376 );
377
378 sub post_checkin_backdate_circ {
379     my( $self, $conn, $auth, $circ_id, $backdate ) = @_;
380
381     my $e = new_editor(authtoken=>$auth, xact=>1);
382     return $e->die_event unless $e->checkauth;
383
384     my $circ = $e->retrieve_action_circulation($circ_id)
385         or return $e->die_event;
386
387     # anyone with checkin perms can backdate (more restrictive?)
388     return $e->die_event unless $e->allowed('COPY_CHECKIN', $circ->circ_lib);
389
390     # don't allow back-dating an open circulation
391     return OpenILS::Event->new('BAD_PARAMS') unless 
392         $backdate and $circ->checkin_time;
393
394     # update the checkin and stop_fines times to reflect the new backdate
395     $circ->stop_fines_time(clense_ISO8601($backdate));
396     $circ->checkin_time(clense_ISO8601($backdate));
397     $e->update_action_circulation($circ) or return $e->die_event;
398
399     # now void the overdues "erased" by the back-dating
400     my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ, $backdate);
401     return $evt if $evt;
402
403     # If the circ was closed before and the balance owned !=0, re-open the transaction
404     $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
405     return $evt if $evt;
406
407     $e->commit;
408     return 1;
409 }
410
411
412
413 __PACKAGE__->register_method (
414         method          => 'set_circ_due_date',
415         api_name                => 'open-ils.circ.circulation.due_date.update',
416         signature       => q/
417                 Updates the due_date on the given circ
418                 @param authtoken
419                 @param circid The id of the circ to update
420                 @param date The timestamp of the new due date
421         /
422 );
423
424 sub set_circ_due_date {
425         my( $self, $conn, $auth, $circ_id, $date ) = @_;
426
427     my $e = new_editor(xact=>1, authtoken=>$auth);
428     return $e->die_event unless $e->checkauth;
429     my $circ = $e->retrieve_action_circulation($circ_id)
430         or return $e->die_event;
431
432     return $e->die_event unless $e->allowed('CIRC_OVERRIDE_DUE_DATE', $circ->circ_lib);
433         $date = clense_ISO8601($date);
434         $circ->due_date($date);
435     $e->update_action_circulation($circ) or return $e->die_event;
436     $e->commit;
437
438     return $circ->id;
439 }
440
441
442 __PACKAGE__->register_method(
443         method          => "create_in_house_use",
444         api_name                => 'open-ils.circ.in_house_use.create',
445         signature       =>      q/
446                 Creates an in-house use action.
447                 @param $authtoken The login session key
448                 @param params A hash of params including
449                         'location' The org unit id where the in-house use occurs
450                         'copyid' The copy in question
451                         'count' The number of in-house uses to apply to this copy
452                 @return An array of id's representing the id's of the newly created
453                 in-house use objects or an event on an error
454         /);
455
456 __PACKAGE__->register_method(
457         method          => "create_in_house_use",
458         api_name                => 'open-ils.circ.non_cat_in_house_use.create',
459 );
460
461
462 sub create_in_house_use {
463         my( $self, $client, $auth, $params ) = @_;
464
465         my( $evt, $copy );
466         my $org                 = $params->{location};
467         my $copyid              = $params->{copyid};
468         my $count               = $params->{count} || 1;
469         my $nc_type             = $params->{non_cat_type};
470         my $use_time    = $params->{use_time} || 'now';
471
472         my $e = new_editor(xact=>1,authtoken=>$auth);
473         return $e->event unless $e->checkauth;
474         return $e->event unless $e->allowed('CREATE_IN_HOUSE_USE');
475
476         my $non_cat = 1 if $self->api_name =~ /non_cat/;
477
478         unless( $non_cat ) {
479                 if( $copyid ) {
480                         $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
481                 } else {
482                         $copy = $e->search_asset_copy({barcode=>$params->{barcode}, deleted => 'f'})->[0]
483                                 or return $e->event;
484                         $copyid = $copy->id;
485                 }
486         }
487
488         if( $use_time ne 'now' ) {
489                 $use_time = clense_ISO8601($use_time);
490                 $logger->debug("in_house_use setting use time to $use_time");
491         }
492
493         my @ids;
494         for(1..$count) {
495
496                 my $ihu;
497                 my $method;
498                 my $cmeth;
499
500                 if($non_cat) {
501                         $ihu = Fieldmapper::action::non_cat_in_house_use->new;
502                         $ihu->item_type($nc_type);
503                         $method = 'open-ils.storage.direct.action.non_cat_in_house_use.create';
504                         $cmeth = "create_action_non_cat_in_house_use";
505
506                 } else {
507                         $ihu = Fieldmapper::action::in_house_use->new;
508                         $ihu->item($copyid);
509                         $method = 'open-ils.storage.direct.action.in_house_use.create';
510                         $cmeth = "create_action_in_house_use";
511                 }
512
513                 $ihu->staff($e->requestor->id);
514                 $ihu->org_unit($org);
515                 $ihu->use_time($use_time);
516
517                 $ihu = $e->$cmeth($ihu) or return $e->event;
518                 push( @ids, $ihu->id );
519         }
520
521         $e->commit;
522         return \@ids;
523 }
524
525
526
527
528
529 __PACKAGE__->register_method(
530         method  => "view_circs",
531         api_name        => "open-ils.circ.copy_checkout_history.retrieve",
532         notes           => q/
533                 Retrieves the last X circs for a given copy
534                 @param authtoken The login session key
535                 @param copyid The copy to check
536                 @param count How far to go back in the item history
537                 @return An array of circ ids
538         /);
539
540 # ----------------------------------------------------------------------
541 # Returns $count most recent circs.  If count exceeds the configured 
542 # max, use the configured max instead
543 # ----------------------------------------------------------------------
544 sub view_circs {
545         my( $self, $client, $authtoken, $copyid, $count ) = @_; 
546
547     my $e = new_editor(authtoken => $authtoken);
548     return $e->event unless $e->checkauth;
549     
550     my $copy = $e->retrieve_asset_copy([
551         $copyid,
552         {   flesh => 1,
553             flesh_fields => {acp => ['call_number']}
554         }
555     ]) or return $e->event;
556
557     return $e->event unless $e->allowed(
558         'VIEW_COPY_CHECKOUT_HISTORY', 
559         ($copy->call_number == OILS_PRECAT_CALL_NUMBER) ? 
560             $copy->circ_lib : $copy->call_number->owning_lib);
561         
562     my $max_history = $U->ou_ancestor_setting_value(
563         $e->requestor->ws_ou, 'circ.item_checkout_history.max', $e);
564
565     if(defined $max_history) {
566         $count = $max_history unless defined $count and $count < $max_history;
567     } else {
568         $count = 4 unless defined $count;
569     }
570
571     return $e->search_action_circulation([
572         {target_copy => $copyid}, 
573         {limit => $count, order_by => { circ => "xact_start DESC" }} 
574     ]);
575 }
576
577
578 __PACKAGE__->register_method(
579         method  => "circ_count",
580         api_name        => "open-ils.circ.circulation.count",
581         notes           => q/
582                 Returns the number of times the item has circulated
583                 @param copyid The copy to check
584         /);
585
586 sub circ_count {
587         my( $self, $client, $copyid, $range ) = @_; 
588         my $e = OpenILS::Utils::Editor->new;
589         return $e->request('open-ils.storage.asset.copy.circ_count', $copyid, $range);
590 }
591
592
593
594 __PACKAGE__->register_method(
595         method          => 'fetch_notes',
596         api_name                => 'open-ils.circ.copy_note.retrieve.all',
597         signature       => q/
598                 Returns an array of copy note objects.  
599                 @param args A named hash of parameters including:
600                         authtoken       : Required if viewing non-public notes
601                         itemid          : The id of the item whose notes we want to retrieve
602                         pub                     : True if all the caller wants are public notes
603                 @return An array of note objects
604         /);
605
606 __PACKAGE__->register_method(
607         method          => 'fetch_notes',
608         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
609         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
610
611 __PACKAGE__->register_method(
612         method          => 'fetch_notes',
613         api_name                => 'open-ils.circ.title_note.retrieve.all',
614         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
615
616
617 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
618 sub fetch_notes {
619         my( $self, $connection, $args ) = @_;
620
621         my $id = $$args{itemid};
622         my $authtoken = $$args{authtoken};
623         my( $r, $evt);
624
625         if( $self->api_name =~ /copy/ ) {
626                 if( $$args{pub} ) {
627                         return $U->cstorereq(
628                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
629                                 { owning_copy => $id, pub => 't' } );
630                 } else {
631                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
632                         return $evt if $evt;
633                         return $U->cstorereq(
634                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
635                 }
636
637         } elsif( $self->api_name =~ /call_number/ ) {
638                 if( $$args{pub} ) {
639                         return $U->cstorereq(
640                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
641                                 { call_number => $id, pub => 't' } );
642                 } else {
643                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
644                         return $evt if $evt;
645                         return $U->cstorereq(
646                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
647                 }
648
649         } elsif( $self->api_name =~ /title/ ) {
650                 if( $$args{pub} ) {
651                         return $U->cstorereq(
652                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
653                                 { record => $id, pub => 't' } );
654                 } else {
655                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
656                         return $evt if $evt;
657                         return $U->cstorereq(
658                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
659                 }
660         }
661
662         return undef;
663 }
664
665 __PACKAGE__->register_method(
666         method  => 'has_notes',
667         api_name        => 'open-ils.circ.copy.has_notes');
668 __PACKAGE__->register_method(
669         method  => 'has_notes',
670         api_name        => 'open-ils.circ.call_number.has_notes');
671 __PACKAGE__->register_method(
672         method  => 'has_notes',
673         api_name        => 'open-ils.circ.title.has_notes');
674
675
676 sub has_notes {
677         my( $self, $conn, $authtoken, $id ) = @_;
678         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
679         return $editor->event unless $editor->checkauth;
680
681         my $n = $editor->search_asset_copy_note(
682                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
683
684         $n = $editor->search_asset_call_number_note(
685                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
686
687         $n = $editor->search_biblio_record_note(
688                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
689
690         return scalar @$n;
691 }
692
693
694
695 __PACKAGE__->register_method(
696         method          => 'create_copy_note',
697         api_name                => 'open-ils.circ.copy_note.create',
698         signature       => q/
699                 Creates a new copy note
700                 @param authtoken The login session key
701                 @param note     The note object to create
702                 @return The id of the new note object
703         /);
704
705 sub create_copy_note {
706         my( $self, $connection, $authtoken, $note ) = @_;
707
708         my $e = new_editor(xact=>1, authtoken=>$authtoken);
709         return $e->event unless $e->checkauth;
710         my $copy = $e->retrieve_asset_copy(
711                 [
712                         $note->owning_copy,
713                         {       flesh => 1,
714                                 flesh_fields => { 'acp' => ['call_number'] }
715                         }
716                 ]
717         );
718
719         return $e->event unless 
720                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
721
722         $note->create_date('now');
723         $note->creator($e->requestor->id);
724         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
725         $note->clear_id;
726
727         $e->create_asset_copy_note($note) or return $e->event;
728         $e->commit;
729         return $note->id;
730 }
731
732
733 __PACKAGE__->register_method(
734         method          => 'delete_copy_note',
735         api_name                =>      'open-ils.circ.copy_note.delete',
736         signature       => q/
737                 Deletes an existing copy note
738                 @param authtoken The login session key
739                 @param noteid The id of the note to delete
740                 @return 1 on success - Event otherwise.
741                 /);
742 sub delete_copy_note {
743         my( $self, $conn, $authtoken, $noteid ) = @_;
744
745         my $e = new_editor(xact=>1, authtoken=>$authtoken);
746         return $e->die_event unless $e->checkauth;
747
748         my $note = $e->retrieve_asset_copy_note([
749                 $noteid,
750                 { flesh => 2,
751                         flesh_fields => {
752                                 'acpn' => [ 'owning_copy' ],
753                                 'acp' => [ 'call_number' ],
754                         }
755                 }
756         ]) or return $e->die_event;
757
758         if( $note->creator ne $e->requestor->id ) {
759                 return $e->die_event unless 
760                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
761         }
762
763         $e->delete_asset_copy_note($note) or return $e->die_event;
764         $e->commit;
765         return 1;
766 }
767
768
769 __PACKAGE__->register_method(
770         method => 'age_hold_rules',
771         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
772 );
773
774 sub age_hold_rules {
775         my( $self, $conn ) = @_;
776         return new_editor()->retrieve_all_config_rules_age_hold_protect();
777 }
778
779
780
781 __PACKAGE__->register_method(
782         method => 'copy_details_barcode',
783     authoritative => 1,
784         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
785 sub copy_details_barcode {
786         my( $self, $conn, $auth, $barcode ) = @_;
787     my $e = new_editor();
788     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
789     return $e->event unless $cid;
790         return copy_details( $self, $conn, $auth, $cid );
791 }
792
793
794 __PACKAGE__->register_method(
795         method => 'copy_details',
796         api_name => 'open-ils.circ.copy_details.retrieve');
797
798 sub copy_details {
799         my( $self, $conn, $auth, $copy_id ) = @_;
800         my $e = new_editor(authtoken=>$auth);
801         return $e->event unless $e->checkauth;
802
803         my $flesh = { flesh => 1 };
804
805         my $copy = $e->retrieve_asset_copy(
806                 [
807                         $copy_id,
808                         {
809                                 flesh => 2,
810                                 flesh_fields => {
811                                         acp => ['call_number'],
812                                         acn => ['record']
813                                 }
814                         }
815                 ]) or return $e->event;
816
817
818         # De-flesh the copy for backwards compatibility
819         my $mvr;
820         my $vol = $copy->call_number;
821         if( ref $vol ) {
822                 $copy->call_number($vol->id);
823                 my $record = $vol->record;
824                 if( ref $record ) {
825                         $vol->record($record->id);
826                         $mvr = $U->record_to_mvr($record);
827                 }
828         }
829
830
831         my $hold = $e->search_action_hold_request(
832                 { 
833                         current_copy            => $copy_id, 
834                         capture_time            => { "!=" => undef },
835                         fulfillment_time        => undef,
836                         cancel_time                     => undef,
837                 }
838         )->[0];
839
840         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
841
842         my $transit = $e->search_action_transit_copy(
843                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
844
845         # find the latest circ, open or closed
846         my $circ = $e->search_action_circulation(
847                 [
848                         { target_copy => $copy_id },
849                         { 
850                 flesh => 1,
851                 flesh_fields => {
852                     circ => [
853                         'checkin_workstation', 
854                         'duration_rule', 
855                         'max_fine_rule', 
856                         'recuring_fine_rule'
857                     ]
858                 },
859                 order_by => { circ => 'xact_start desc' }, 
860                 limit => 1 
861             }
862                 ]
863         )->[0];
864
865
866         return {
867                 copy            => $copy,
868                 hold            => $hold,
869                 transit => $transit,
870                 circ            => $circ,
871                 volume  => $vol,
872                 mvr             => $mvr,
873         };
874 }
875
876
877
878
879 __PACKAGE__->register_method(
880         method => 'mark_item',
881         api_name => 'open-ils.circ.mark_item_damaged',
882         signature       => q/
883                 Changes the status of a copy to "damaged". Requires MARK_ITEM_DAMAGED permission.
884                 @param authtoken The login session key
885                 @param copy_id The ID of the copy to mark as damaged
886                 @return 1 on success - Event otherwise.
887                 /
888 );
889 __PACKAGE__->register_method(
890         method => 'mark_item',
891         api_name => 'open-ils.circ.mark_item_missing',
892         signature       => q/
893                 Changes the status of a copy to "missing". Requires MARK_ITEM_MISSING permission.
894                 @param authtoken The login session key
895                 @param copy_id The ID of the copy to mark as missing 
896                 @return 1 on success - Event otherwise.
897                 /
898 );
899 __PACKAGE__->register_method(
900         method => 'mark_item',
901         api_name => 'open-ils.circ.mark_item_bindery',
902         signature       => q/
903                 Changes the status of a copy to "bindery". Requires MARK_ITEM_BINDERY permission.
904                 @param authtoken The login session key
905                 @param copy_id The ID of the copy to mark as bindery
906                 @return 1 on success - Event otherwise.
907                 /
908 );
909 __PACKAGE__->register_method(
910         method => 'mark_item',
911         api_name => 'open-ils.circ.mark_item_on_order',
912         signature       => q/
913                 Changes the status of a copy to "on order". Requires MARK_ITEM_ON_ORDER permission.
914                 @param authtoken The login session key
915                 @param copy_id The ID of the copy to mark as on order 
916                 @return 1 on success - Event otherwise.
917                 /
918 );
919 __PACKAGE__->register_method(
920         method => 'mark_item',
921         api_name => 'open-ils.circ.mark_item_ill',
922         signature       => q/
923                 Changes the status of a copy to "inter-library loan". Requires MARK_ITEM_ILL permission.
924                 @param authtoken The login session key
925                 @param copy_id The ID of the copy to mark as inter-library loan
926                 @return 1 on success - Event otherwise.
927                 /
928 );
929 __PACKAGE__->register_method(
930         method => 'mark_item',
931         api_name => 'open-ils.circ.mark_item_cataloging',
932         signature       => q/
933                 Changes the status of a copy to "cataloging". Requires MARK_ITEM_CATALOGING permission.
934                 @param authtoken The login session key
935                 @param copy_id The ID of the copy to mark as cataloging 
936                 @return 1 on success - Event otherwise.
937                 /
938 );
939 __PACKAGE__->register_method(
940         method => 'mark_item',
941         api_name => 'open-ils.circ.mark_item_reserves',
942         signature       => q/
943                 Changes the status of a copy to "reserves". Requires MARK_ITEM_RESERVES permission.
944                 @param authtoken The login session key
945                 @param copy_id The ID of the copy to mark as reserves
946                 @return 1 on success - Event otherwise.
947                 /
948 );
949 __PACKAGE__->register_method(
950         method => 'mark_item',
951         api_name => 'open-ils.circ.mark_item_discard',
952         signature       => q/
953                 Changes the status of a copy to "discard". Requires MARK_ITEM_DISCARD permission.
954                 @param authtoken The login session key
955                 @param copy_id The ID of the copy to mark as discard
956                 @return 1 on success - Event otherwise.
957                 /
958 );
959
960 sub mark_item {
961         my( $self, $conn, $auth, $copy_id, $args ) = @_;
962         my $e = new_editor(authtoken=>$auth, xact =>1);
963         return $e->die_event unless $e->checkauth;
964     $args ||= {};
965
966     my $copy = $e->retrieve_asset_copy([
967         $copy_id,
968         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
969             or return $e->die_event;
970
971     my $owning_lib = 
972         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
973             $copy->circ_lib : $copy->call_number->owning_lib;
974
975     return $e->die_event unless $e->allowed('UPDATE_COPY', $owning_lib);
976
977
978         my $perm = 'MARK_ITEM_MISSING';
979         my $stat = OILS_COPY_STATUS_MISSING;
980
981         if( $self->api_name =~ /damaged/ ) {
982                 $perm = 'MARK_ITEM_DAMAGED';
983                 $stat = OILS_COPY_STATUS_DAMAGED;
984         my $evt = handle_mark_damaged($e, $copy, $owning_lib, $args);
985         return $evt if $evt;
986
987         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
988         $ses->request('open-ils.trigger.event.autocreate', 'damaged', $copy, $owning_lib);
989
990         } elsif ( $self->api_name =~ /bindery/ ) {
991                 $perm = 'MARK_ITEM_BINDERY';
992                 $stat = OILS_COPY_STATUS_BINDERY;
993         } elsif ( $self->api_name =~ /on_order/ ) {
994                 $perm = 'MARK_ITEM_ON_ORDER';
995                 $stat = OILS_COPY_STATUS_ON_ORDER;
996         } elsif ( $self->api_name =~ /ill/ ) {
997                 $perm = 'MARK_ITEM_ILL';
998                 $stat = OILS_COPY_STATUS_ILL;
999         } elsif ( $self->api_name =~ /cataloging/ ) {
1000                 $perm = 'MARK_ITEM_CATALOGING';
1001                 $stat = OILS_COPY_STATUS_CATALOGING;
1002         } elsif ( $self->api_name =~ /reserves/ ) {
1003                 $perm = 'MARK_ITEM_RESERVES';
1004                 $stat = OILS_COPY_STATUS_RESERVES;
1005         } elsif ( $self->api_name =~ /discard/ ) {
1006                 $perm = 'MARK_ITEM_DISCARD';
1007                 $stat = OILS_COPY_STATUS_DISCARD;
1008         }
1009
1010
1011         $copy->status($stat);
1012         $copy->edit_date('now');
1013         $copy->editor($e->requestor->id);
1014
1015         $e->update_asset_copy($copy) or return $e->die_event;
1016
1017         my $holds = $e->search_action_hold_request(
1018                 { 
1019                         current_copy => $copy->id,
1020                         fulfillment_time => undef,
1021                         cancel_time => undef,
1022                 }
1023         );
1024
1025         $e->commit;
1026
1027         $logger->debug("resetting holds that target the marked copy");
1028         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
1029
1030         return 1;
1031 }
1032
1033 sub handle_mark_damaged {
1034     my($e, $copy, $owning_lib, $args) = @_;
1035
1036     my $apply = $args->{apply_fines} || '';
1037     return undef if $apply eq 'noapply';
1038
1039     # grab the last circulation
1040     my $circ = $e->search_action_circulation([
1041         {   target_copy => $copy->id}, 
1042         {   limit => 1, 
1043             order_by => {circ => "xact_start DESC"},
1044             flesh => 2,
1045             flesh_fields => {circ => ['target_copy', 'usr'], au => ['card']}
1046         }
1047     ])->[0];
1048
1049     return undef unless $circ;
1050
1051     my $charge_price = $U->ou_ancestor_setting_value(
1052         $owning_lib, 'circ.charge_on_damaged', $e);
1053
1054     my $proc_fee = $U->ou_ancestor_setting_value(
1055         $owning_lib, 'circ.damaged_item_processing_fee', $e) || 0;
1056
1057     return undef unless $charge_price or $proc_fee;
1058
1059     my $copy_price = ($charge_price) ? $U->get_copy_price($e, $copy) : 0;
1060     my $total = $copy_price + $proc_fee;
1061
1062     if($apply) {
1063         
1064         if($charge_price and $copy_price) {
1065             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1066                 $e, $copy_price, 7, 'Damaged Item', $circ->id);
1067             return $evt if $evt;
1068         }
1069
1070         if($proc_fee) {
1071             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1072                 $e, $proc_fee, 8, 'Damaged Item Processing Fee', $circ->id);
1073             return $evt if $evt;
1074         }
1075
1076         my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
1077         return $evt if $evt;
1078
1079         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1080         $ses->request('open-ils.trigger.event.autocreate', 'checkout.damaged', $circ, $circ->circ_lib);
1081
1082         return undef;
1083
1084     } else {
1085         return OpenILS::Event->new('DAMAGE_CHARGE', 
1086             payload => {
1087                 circ => $circ,
1088                 charge => $total
1089             }
1090         );
1091     }
1092 }
1093
1094
1095
1096
1097
1098
1099 # ----------------------------------------------------------------------
1100 __PACKAGE__->register_method(
1101         method => 'magic_fetch',
1102         api_name => 'open-ils.agent.fetch'
1103 );
1104
1105 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
1106
1107 sub magic_fetch {
1108         my( $self, $conn, $auth, $args ) = @_;
1109         my $e = new_editor( authtoken => $auth );
1110         return $e->event unless $e->checkauth;
1111
1112         my $hint = $$args{hint};
1113         my $id  = $$args{id};
1114
1115         # Is the call allowed to fetch this type of object?
1116         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
1117
1118         # Find the class the implements the given hint
1119         my ($class) = grep { 
1120                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
1121
1122         $class =~ s/Fieldmapper:://og;
1123         $class =~ s/::/_/og;
1124         my $method = "retrieve_$class";
1125
1126         my $obj = $e->$method($id) or return $e->event;
1127         return $obj;
1128 }
1129 # ----------------------------------------------------------------------
1130
1131
1132 __PACKAGE__->register_method(
1133         method  => "fleshed_circ_retrieve",
1134     authoritative => 1,
1135         api_name        => "open-ils.circ.fleshed.retrieve",);
1136
1137 sub fleshed_circ_retrieve {
1138         my( $self, $client, $id ) = @_;
1139         my $e = new_editor();
1140         my $circ = $e->retrieve_action_circulation(
1141                 [
1142                         $id,
1143                         { 
1144                                 flesh                           => 4,
1145                                 flesh_fields    => { 
1146                                         circ => [ qw/ target_copy / ],
1147                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1148                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1149                                         acn => [ qw/ record / ],
1150                                 }
1151                         }
1152                 ]
1153         ) or return $e->event;
1154         
1155         my $copy = $circ->target_copy;
1156         my $vol = $copy->call_number;
1157         my $rec = $circ->target_copy->call_number->record;
1158
1159         $vol->record($rec->id);
1160         $copy->call_number($vol->id);
1161         $circ->target_copy($copy->id);
1162
1163         my $mvr;
1164
1165         if( $rec->id == OILS_PRECAT_RECORD ) {
1166                 $rec = undef;
1167                 $vol = undef;
1168         } else { 
1169                 $mvr = $U->record_to_mvr($rec);
1170                 $rec->marc(''); # drop the bulky marc data
1171         }
1172
1173         return {
1174                 circ => $circ,
1175                 copy => $copy,
1176                 volume => $vol,
1177                 record => $rec,
1178                 mvr => $mvr,
1179         };
1180 }
1181
1182
1183
1184 __PACKAGE__->register_method(
1185         method  => "test_batch_circ_events",
1186         api_name        => "open-ils.circ.trigger_event_by_def_and_barcode.fire"
1187 );
1188
1189 #  method for testing the behavior of a given event definition
1190 sub test_batch_circ_events {
1191     my($self, $conn, $auth, $event_def, $barcode) = @_;
1192
1193     my $e = new_editor(authtoken => $auth);
1194         return $e->event unless $e->checkauth;
1195     return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1196
1197     my $copy = $e->search_asset_copy({barcode => $barcode, deleted => 'f'})->[0]
1198         or return $e->event;
1199
1200     my $circ = $e->search_action_circulation(
1201         {target_copy => $copy->id, checkin_time => undef})->[0]
1202         or return $e->event;
1203         
1204     return undef unless $circ;
1205
1206     return $U->fire_object_event($event_def, undef, $circ, $e->requestor->ws_ou)
1207 }
1208
1209
1210
1211 __PACKAGE__->register_method(
1212         method  => "user_payments_list",
1213         api_name        => "open-ils.circ.user_payments.filtered.batch",
1214     stream => 1,
1215         signature => {
1216         desc => q/Returns a fleshed, date-limited set of all payments a user
1217                 has made.  By default, ordered by payment date.  Optionally
1218                 ordered by other columns in the top-level "mp" object/,
1219         params => [
1220             {desc => 'Authentication token', type => 'string'},
1221             {desc => 'User ID', type => 'number'},
1222             {desc => 'Order by column(s), optional.  Array of "mp" class columns', type => 'array'}
1223         ],
1224         return => {desc => q/List of "mp" objects, fleshed with the billable transaction 
1225             and the related fully-realized payment object (e.g money.cash_payment)/}
1226     }
1227 );
1228
1229 sub user_payments_list {
1230     my($self, $conn, $auth, $user_id, $start_date, $end_date, $order_by) = @_;
1231
1232     my $e = new_editor(authtoken => $auth);
1233     return $e->event unless $e->checkauth;
1234
1235     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1236     return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $user->home_ou);
1237
1238     $order_by ||= ['payment_ts'];
1239
1240     # all payments by user, between start_date and end_date
1241     my $payments = $e->json_query({
1242         select => {mp => ['id']}, 
1243         from => {
1244             mp => {
1245                 mbt => {
1246                     fkey => 'xact', field => 'id'}
1247             }
1248         }, 
1249         where => {
1250             '+mbt' => {usr => $user_id}, 
1251             '+mp' => {payment_ts => {between => [$start_date, $end_date]}}
1252         },
1253         order_by => {mp => $order_by}
1254     });
1255
1256     for my $payment_id (@$payments) {
1257         my $payment = $e->retrieve_money_payment([
1258             $payment_id->{id}, 
1259             {   
1260                 flesh => 2,
1261                 flesh_fields => {
1262                     mp => [
1263                         'xact',
1264                         'cash_payment',
1265                         'credit_card_payment',
1266                         'credit_payment',
1267                         'check_payment',
1268                         'work_payment',
1269                         'forgive_payment',
1270                         'goods_payment'
1271                     ],
1272                     mbt => [
1273                         'circulation', 
1274                         'grocery'
1275                     ]
1276                 }
1277             }
1278         ]);
1279         $conn->respond($payment);
1280     }
1281
1282     return undef;
1283 }
1284
1285
1286 # {"select":{"acp":["id"],"circ":[{"aggregate":true,"transform":"count","alias":"count","column":"id"}]},"from":{"acp":{"circ":{"field":"target_copy","fkey":"id","type":"left"},"acn"{"field":"id","fkey":"call_number"}}},"where":{"+acn":{"record":200057}}
1287
1288
1289 1;