]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
new feature: Added max-claims-returned-count setting. if a patron hits this amount...
[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
365
366
367 __PACKAGE__->register_method (
368         method          => 'set_circ_due_date',
369         api_name                => 'open-ils.circ.circulation.due_date.update',
370         signature       => q/
371                 Updates the due_date on the given circ
372                 @param authtoken
373                 @param circid The id of the circ to update
374                 @param date The timestamp of the new due date
375         /
376 );
377
378 sub set_circ_due_date {
379         my( $self, $conn, $auth, $circ_id, $date ) = @_;
380
381     my $e = new_editor(xact=>1, authtoken=>$auth);
382     return $e->die_event unless $e->checkauth;
383     my $circ = $e->retrieve_action_circulation($circ_id)
384         or return $e->die_event;
385
386     return $e->die_event unless $e->allowed('CIRC_OVERRIDE_DUE_DATE', $circ->circ_lib);
387         $date = clense_ISO8601($date);
388         $circ->due_date($date);
389     $e->update_action_circulation($circ) or return $e->die_event;
390     $e->commit;
391
392     return $circ->id;
393 }
394
395
396 __PACKAGE__->register_method(
397         method          => "create_in_house_use",
398         api_name                => 'open-ils.circ.in_house_use.create',
399         signature       =>      q/
400                 Creates an in-house use action.
401                 @param $authtoken The login session key
402                 @param params A hash of params including
403                         'location' The org unit id where the in-house use occurs
404                         'copyid' The copy in question
405                         'count' The number of in-house uses to apply to this copy
406                 @return An array of id's representing the id's of the newly created
407                 in-house use objects or an event on an error
408         /);
409
410 __PACKAGE__->register_method(
411         method          => "create_in_house_use",
412         api_name                => 'open-ils.circ.non_cat_in_house_use.create',
413 );
414
415
416 sub create_in_house_use {
417         my( $self, $client, $auth, $params ) = @_;
418
419         my( $evt, $copy );
420         my $org                 = $params->{location};
421         my $copyid              = $params->{copyid};
422         my $count               = $params->{count} || 1;
423         my $nc_type             = $params->{non_cat_type};
424         my $use_time    = $params->{use_time} || 'now';
425
426         my $e = new_editor(xact=>1,authtoken=>$auth);
427         return $e->event unless $e->checkauth;
428         return $e->event unless $e->allowed('CREATE_IN_HOUSE_USE');
429
430         my $non_cat = 1 if $self->api_name =~ /non_cat/;
431
432         unless( $non_cat ) {
433                 if( $copyid ) {
434                         $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
435                 } else {
436                         $copy = $e->search_asset_copy({barcode=>$params->{barcode}, deleted => 'f'})->[0]
437                                 or return $e->event;
438                         $copyid = $copy->id;
439                 }
440         }
441
442         if( $use_time ne 'now' ) {
443                 $use_time = clense_ISO8601($use_time);
444                 $logger->debug("in_house_use setting use time to $use_time");
445         }
446
447         my @ids;
448         for(1..$count) {
449
450                 my $ihu;
451                 my $method;
452                 my $cmeth;
453
454                 if($non_cat) {
455                         $ihu = Fieldmapper::action::non_cat_in_house_use->new;
456                         $ihu->item_type($nc_type);
457                         $method = 'open-ils.storage.direct.action.non_cat_in_house_use.create';
458                         $cmeth = "create_action_non_cat_in_house_use";
459
460                 } else {
461                         $ihu = Fieldmapper::action::in_house_use->new;
462                         $ihu->item($copyid);
463                         $method = 'open-ils.storage.direct.action.in_house_use.create';
464                         $cmeth = "create_action_in_house_use";
465                 }
466
467                 $ihu->staff($e->requestor->id);
468                 $ihu->org_unit($org);
469                 $ihu->use_time($use_time);
470
471                 $ihu = $e->$cmeth($ihu) or return $e->event;
472                 push( @ids, $ihu->id );
473         }
474
475         $e->commit;
476         return \@ids;
477 }
478
479
480
481
482
483 __PACKAGE__->register_method(
484         method  => "view_circs",
485         api_name        => "open-ils.circ.copy_checkout_history.retrieve",
486         notes           => q/
487                 Retrieves the last X circs for a given copy
488                 @param authtoken The login session key
489                 @param copyid The copy to check
490                 @param count How far to go back in the item history
491                 @return An array of circ ids
492         /);
493
494 # ----------------------------------------------------------------------
495 # Returns $count most recent circs.  If count exceeds the configured 
496 # max, use the configured max instead
497 # ----------------------------------------------------------------------
498 sub view_circs {
499         my( $self, $client, $authtoken, $copyid, $count ) = @_; 
500
501     my $e = new_editor(authtoken => $authtoken);
502     return $e->event unless $e->checkauth;
503     
504     my $copy = $e->retrieve_asset_copy([
505         $copyid,
506         {   flesh => 1,
507             flesh_fields => {acp => ['call_number']}
508         }
509     ]) or return $e->event;
510
511     return $e->event unless $e->allowed(
512         'VIEW_COPY_CHECKOUT_HISTORY', 
513         ($copy->call_number == OILS_PRECAT_CALL_NUMBER) ? 
514             $copy->circ_lib : $copy->call_number->owning_lib);
515         
516     my $max_history = $U->ou_ancestor_setting_value(
517         $e->requestor->ws_ou, 'circ.item_checkout_history.max', $e);
518
519     if(defined $max_history) {
520         $count = $max_history unless defined $count and $count < $max_history;
521     } else {
522         $count = 4 unless defined $count;
523     }
524
525     return $e->search_action_circulation([
526         {target_copy => $copyid}, 
527         {limit => $count, order_by => { circ => "xact_start DESC" }} 
528     ]);
529 }
530
531
532 __PACKAGE__->register_method(
533         method  => "circ_count",
534         api_name        => "open-ils.circ.circulation.count",
535         notes           => q/
536                 Returns the number of times the item has circulated
537                 @param copyid The copy to check
538         /);
539
540 sub circ_count {
541         my( $self, $client, $copyid, $range ) = @_; 
542         my $e = OpenILS::Utils::Editor->new;
543         return $e->request('open-ils.storage.asset.copy.circ_count', $copyid, $range);
544 }
545
546
547
548 __PACKAGE__->register_method(
549         method          => 'fetch_notes',
550         api_name                => 'open-ils.circ.copy_note.retrieve.all',
551         signature       => q/
552                 Returns an array of copy note objects.  
553                 @param args A named hash of parameters including:
554                         authtoken       : Required if viewing non-public notes
555                         itemid          : The id of the item whose notes we want to retrieve
556                         pub                     : True if all the caller wants are public notes
557                 @return An array of note objects
558         /);
559
560 __PACKAGE__->register_method(
561         method          => 'fetch_notes',
562         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
563         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
564
565 __PACKAGE__->register_method(
566         method          => 'fetch_notes',
567         api_name                => 'open-ils.circ.title_note.retrieve.all',
568         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
569
570
571 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
572 sub fetch_notes {
573         my( $self, $connection, $args ) = @_;
574
575         my $id = $$args{itemid};
576         my $authtoken = $$args{authtoken};
577         my( $r, $evt);
578
579         if( $self->api_name =~ /copy/ ) {
580                 if( $$args{pub} ) {
581                         return $U->cstorereq(
582                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
583                                 { owning_copy => $id, pub => 't' } );
584                 } else {
585                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
586                         return $evt if $evt;
587                         return $U->cstorereq(
588                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
589                 }
590
591         } elsif( $self->api_name =~ /call_number/ ) {
592                 if( $$args{pub} ) {
593                         return $U->cstorereq(
594                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
595                                 { call_number => $id, pub => 't' } );
596                 } else {
597                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
598                         return $evt if $evt;
599                         return $U->cstorereq(
600                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
601                 }
602
603         } elsif( $self->api_name =~ /title/ ) {
604                 if( $$args{pub} ) {
605                         return $U->cstorereq(
606                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
607                                 { record => $id, pub => 't' } );
608                 } else {
609                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
610                         return $evt if $evt;
611                         return $U->cstorereq(
612                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
613                 }
614         }
615
616         return undef;
617 }
618
619 __PACKAGE__->register_method(
620         method  => 'has_notes',
621         api_name        => 'open-ils.circ.copy.has_notes');
622 __PACKAGE__->register_method(
623         method  => 'has_notes',
624         api_name        => 'open-ils.circ.call_number.has_notes');
625 __PACKAGE__->register_method(
626         method  => 'has_notes',
627         api_name        => 'open-ils.circ.title.has_notes');
628
629
630 sub has_notes {
631         my( $self, $conn, $authtoken, $id ) = @_;
632         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
633         return $editor->event unless $editor->checkauth;
634
635         my $n = $editor->search_asset_copy_note(
636                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
637
638         $n = $editor->search_asset_call_number_note(
639                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
640
641         $n = $editor->search_biblio_record_note(
642                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
643
644         return scalar @$n;
645 }
646
647
648
649 __PACKAGE__->register_method(
650         method          => 'create_copy_note',
651         api_name                => 'open-ils.circ.copy_note.create',
652         signature       => q/
653                 Creates a new copy note
654                 @param authtoken The login session key
655                 @param note     The note object to create
656                 @return The id of the new note object
657         /);
658
659 sub create_copy_note {
660         my( $self, $connection, $authtoken, $note ) = @_;
661
662         my $e = new_editor(xact=>1, authtoken=>$authtoken);
663         return $e->event unless $e->checkauth;
664         my $copy = $e->retrieve_asset_copy(
665                 [
666                         $note->owning_copy,
667                         {       flesh => 1,
668                                 flesh_fields => { 'acp' => ['call_number'] }
669                         }
670                 ]
671         );
672
673         return $e->event unless 
674                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
675
676         $note->create_date('now');
677         $note->creator($e->requestor->id);
678         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
679         $note->clear_id;
680
681         $e->create_asset_copy_note($note) or return $e->event;
682         $e->commit;
683         return $note->id;
684 }
685
686
687 __PACKAGE__->register_method(
688         method          => 'delete_copy_note',
689         api_name                =>      'open-ils.circ.copy_note.delete',
690         signature       => q/
691                 Deletes an existing copy note
692                 @param authtoken The login session key
693                 @param noteid The id of the note to delete
694                 @return 1 on success - Event otherwise.
695                 /);
696 sub delete_copy_note {
697         my( $self, $conn, $authtoken, $noteid ) = @_;
698
699         my $e = new_editor(xact=>1, authtoken=>$authtoken);
700         return $e->die_event unless $e->checkauth;
701
702         my $note = $e->retrieve_asset_copy_note([
703                 $noteid,
704                 { flesh => 2,
705                         flesh_fields => {
706                                 'acpn' => [ 'owning_copy' ],
707                                 'acp' => [ 'call_number' ],
708                         }
709                 }
710         ]) or return $e->die_event;
711
712         if( $note->creator ne $e->requestor->id ) {
713                 return $e->die_event unless 
714                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
715         }
716
717         $e->delete_asset_copy_note($note) or return $e->die_event;
718         $e->commit;
719         return 1;
720 }
721
722
723 __PACKAGE__->register_method(
724         method => 'age_hold_rules',
725         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
726 );
727
728 sub age_hold_rules {
729         my( $self, $conn ) = @_;
730         return new_editor()->retrieve_all_config_rules_age_hold_protect();
731 }
732
733
734
735 __PACKAGE__->register_method(
736         method => 'copy_details_barcode',
737     authoritative => 1,
738         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
739 sub copy_details_barcode {
740         my( $self, $conn, $auth, $barcode ) = @_;
741     my $e = new_editor();
742     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
743     return $e->event unless $cid;
744         return copy_details( $self, $conn, $auth, $cid );
745 }
746
747
748 __PACKAGE__->register_method(
749         method => 'copy_details',
750         api_name => 'open-ils.circ.copy_details.retrieve');
751
752 sub copy_details {
753         my( $self, $conn, $auth, $copy_id ) = @_;
754         my $e = new_editor(authtoken=>$auth);
755         return $e->event unless $e->checkauth;
756
757         my $flesh = { flesh => 1 };
758
759         my $copy = $e->retrieve_asset_copy(
760                 [
761                         $copy_id,
762                         {
763                                 flesh => 2,
764                                 flesh_fields => {
765                                         acp => ['call_number'],
766                                         acn => ['record']
767                                 }
768                         }
769                 ]) or return $e->event;
770
771
772         # De-flesh the copy for backwards compatibility
773         my $mvr;
774         my $vol = $copy->call_number;
775         if( ref $vol ) {
776                 $copy->call_number($vol->id);
777                 my $record = $vol->record;
778                 if( ref $record ) {
779                         $vol->record($record->id);
780                         $mvr = $U->record_to_mvr($record);
781                 }
782         }
783
784
785         my $hold = $e->search_action_hold_request(
786                 { 
787                         current_copy            => $copy_id, 
788                         capture_time            => { "!=" => undef },
789                         fulfillment_time        => undef,
790                         cancel_time                     => undef,
791                 }
792         )->[0];
793
794         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
795
796         my $transit = $e->search_action_transit_copy(
797                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
798
799         # find the latest circ, open or closed
800         my $circ = $e->search_action_circulation(
801                 [
802                         { target_copy => $copy_id },
803                         { 
804                 flesh => 1,
805                 flesh_fields => {circ => ['checkin_workstation']},
806                 order_by => { circ => 'xact_start desc' }, 
807                 limit => 1 
808             }
809                 ]
810         )->[0];
811
812
813         return {
814                 copy            => $copy,
815                 hold            => $hold,
816                 transit => $transit,
817                 circ            => $circ,
818                 volume  => $vol,
819                 mvr             => $mvr,
820         };
821 }
822
823
824
825
826 __PACKAGE__->register_method(
827         method => 'mark_item',
828         api_name => 'open-ils.circ.mark_item_damaged',
829         signature       => q/
830                 Changes the status of a copy to "damaged". Requires MARK_ITEM_DAMAGED permission.
831                 @param authtoken The login session key
832                 @param copy_id The ID of the copy to mark as damaged
833                 @return 1 on success - Event otherwise.
834                 /
835 );
836 __PACKAGE__->register_method(
837         method => 'mark_item',
838         api_name => 'open-ils.circ.mark_item_missing',
839         signature       => q/
840                 Changes the status of a copy to "missing". Requires MARK_ITEM_MISSING permission.
841                 @param authtoken The login session key
842                 @param copy_id The ID of the copy to mark as missing 
843                 @return 1 on success - Event otherwise.
844                 /
845 );
846 __PACKAGE__->register_method(
847         method => 'mark_item',
848         api_name => 'open-ils.circ.mark_item_bindery',
849         signature       => q/
850                 Changes the status of a copy to "bindery". Requires MARK_ITEM_BINDERY permission.
851                 @param authtoken The login session key
852                 @param copy_id The ID of the copy to mark as bindery
853                 @return 1 on success - Event otherwise.
854                 /
855 );
856 __PACKAGE__->register_method(
857         method => 'mark_item',
858         api_name => 'open-ils.circ.mark_item_on_order',
859         signature       => q/
860                 Changes the status of a copy to "on order". Requires MARK_ITEM_ON_ORDER permission.
861                 @param authtoken The login session key
862                 @param copy_id The ID of the copy to mark as on order 
863                 @return 1 on success - Event otherwise.
864                 /
865 );
866 __PACKAGE__->register_method(
867         method => 'mark_item',
868         api_name => 'open-ils.circ.mark_item_ill',
869         signature       => q/
870                 Changes the status of a copy to "inter-library loan". Requires MARK_ITEM_ILL permission.
871                 @param authtoken The login session key
872                 @param copy_id The ID of the copy to mark as inter-library loan
873                 @return 1 on success - Event otherwise.
874                 /
875 );
876 __PACKAGE__->register_method(
877         method => 'mark_item',
878         api_name => 'open-ils.circ.mark_item_cataloging',
879         signature       => q/
880                 Changes the status of a copy to "cataloging". Requires MARK_ITEM_CATALOGING permission.
881                 @param authtoken The login session key
882                 @param copy_id The ID of the copy to mark as cataloging 
883                 @return 1 on success - Event otherwise.
884                 /
885 );
886 __PACKAGE__->register_method(
887         method => 'mark_item',
888         api_name => 'open-ils.circ.mark_item_reserves',
889         signature       => q/
890                 Changes the status of a copy to "reserves". Requires MARK_ITEM_RESERVES permission.
891                 @param authtoken The login session key
892                 @param copy_id The ID of the copy to mark as reserves
893                 @return 1 on success - Event otherwise.
894                 /
895 );
896 __PACKAGE__->register_method(
897         method => 'mark_item',
898         api_name => 'open-ils.circ.mark_item_discard',
899         signature       => q/
900                 Changes the status of a copy to "discard". Requires MARK_ITEM_DISCARD permission.
901                 @param authtoken The login session key
902                 @param copy_id The ID of the copy to mark as discard
903                 @return 1 on success - Event otherwise.
904                 /
905 );
906
907 sub mark_item {
908         my( $self, $conn, $auth, $copy_id, $args ) = @_;
909         my $e = new_editor(authtoken=>$auth, xact =>1);
910         return $e->die_event unless $e->checkauth;
911     $args ||= {};
912
913     my $copy = $e->retrieve_asset_copy([
914         $copy_id,
915         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
916             or return $e->die_event;
917
918     my $owning_lib = 
919         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
920             $copy->circ_lib : $copy->call_number->owning_lib;
921
922     return $e->die_event unless $e->allowed('UPDATE_COPY', $owning_lib);
923
924
925         my $perm = 'MARK_ITEM_MISSING';
926         my $stat = OILS_COPY_STATUS_MISSING;
927
928         if( $self->api_name =~ /damaged/ ) {
929                 $perm = 'MARK_ITEM_DAMAGED';
930                 $stat = OILS_COPY_STATUS_DAMAGED;
931         my $evt = handle_mark_damaged($e, $copy, $owning_lib, $args);
932         return $evt if $evt;
933
934         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
935         $ses->request('open-ils.trigger.event.autocreate', 'damaged', $copy, $owning_lib);
936
937         } elsif ( $self->api_name =~ /bindery/ ) {
938                 $perm = 'MARK_ITEM_BINDERY';
939                 $stat = OILS_COPY_STATUS_BINDERY;
940         } elsif ( $self->api_name =~ /on_order/ ) {
941                 $perm = 'MARK_ITEM_ON_ORDER';
942                 $stat = OILS_COPY_STATUS_ON_ORDER;
943         } elsif ( $self->api_name =~ /ill/ ) {
944                 $perm = 'MARK_ITEM_ILL';
945                 $stat = OILS_COPY_STATUS_ILL;
946         } elsif ( $self->api_name =~ /cataloging/ ) {
947                 $perm = 'MARK_ITEM_CATALOGING';
948                 $stat = OILS_COPY_STATUS_CATALOGING;
949         } elsif ( $self->api_name =~ /reserves/ ) {
950                 $perm = 'MARK_ITEM_RESERVES';
951                 $stat = OILS_COPY_STATUS_RESERVES;
952         } elsif ( $self->api_name =~ /discard/ ) {
953                 $perm = 'MARK_ITEM_DISCARD';
954                 $stat = OILS_COPY_STATUS_DISCARD;
955         }
956
957
958         $copy->status($stat);
959         $copy->edit_date('now');
960         $copy->editor($e->requestor->id);
961
962         $e->update_asset_copy($copy) or return $e->die_event;
963
964         my $holds = $e->search_action_hold_request(
965                 { 
966                         current_copy => $copy->id,
967                         fulfillment_time => undef,
968                         cancel_time => undef,
969                 }
970         );
971
972         $e->commit;
973
974         $logger->debug("resetting holds that target the marked copy");
975         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
976
977         return 1;
978 }
979
980 sub handle_mark_damaged {
981     my($e, $copy, $owning_lib, $args) = @_;
982
983     my $apply = $args->{apply_fines} || '';
984     return undef if $apply eq 'noapply';
985
986     # grab the last circulation
987     my $circ = $e->search_action_circulation([
988         {   target_copy => $copy->id}, 
989         {   limit => 1, 
990             order_by => {circ => "xact_start DESC"},
991             flesh => 2,
992             flesh_fields => {circ => ['target_copy', 'usr'], au => ['card']}
993         }
994     ])->[0];
995
996     return undef unless $circ;
997
998     my $charge_price = $U->ou_ancestor_setting_value(
999         $owning_lib, 'circ.charge_on_damaged', $e);
1000
1001     my $proc_fee = $U->ou_ancestor_setting_value(
1002         $owning_lib, 'circ.damaged_item_processing_fee', $e) || 0;
1003
1004     return undef unless $charge_price or $proc_fee;
1005
1006     my $copy_price = ($charge_price) ? $U->get_copy_price($e, $copy) : 0;
1007     my $total = $copy_price + $proc_fee;
1008
1009     if($apply) {
1010         
1011         if($charge_price and $copy_price) {
1012             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1013                 $e, $copy_price, 7, 'Damaged Item', $circ->id);
1014             return $evt if $evt;
1015         }
1016
1017         if($proc_fee) {
1018             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1019                 $e, $proc_fee, 8, 'Damaged Item Processing Fee', $circ->id);
1020             return $evt if $evt;
1021         }
1022
1023         my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
1024         return $evt if $evt;
1025
1026         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1027         $ses->request('open-ils.trigger.event.autocreate', 'checkout.damaged', $circ, $circ->circ_lib);
1028
1029         return undef;
1030
1031     } else {
1032         return OpenILS::Event->new('DAMAGE_CHARGE', 
1033             payload => {
1034                 circ => $circ,
1035                 charge => $total
1036             }
1037         );
1038     }
1039 }
1040
1041
1042
1043
1044
1045
1046 # ----------------------------------------------------------------------
1047 __PACKAGE__->register_method(
1048         method => 'magic_fetch',
1049         api_name => 'open-ils.agent.fetch'
1050 );
1051
1052 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
1053
1054 sub magic_fetch {
1055         my( $self, $conn, $auth, $args ) = @_;
1056         my $e = new_editor( authtoken => $auth );
1057         return $e->event unless $e->checkauth;
1058
1059         my $hint = $$args{hint};
1060         my $id  = $$args{id};
1061
1062         # Is the call allowed to fetch this type of object?
1063         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
1064
1065         # Find the class the implements the given hint
1066         my ($class) = grep { 
1067                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
1068
1069         $class =~ s/Fieldmapper:://og;
1070         $class =~ s/::/_/og;
1071         my $method = "retrieve_$class";
1072
1073         my $obj = $e->$method($id) or return $e->event;
1074         return $obj;
1075 }
1076 # ----------------------------------------------------------------------
1077
1078
1079 __PACKAGE__->register_method(
1080         method  => "fleshed_circ_retrieve",
1081     authoritative => 1,
1082         api_name        => "open-ils.circ.fleshed.retrieve",);
1083
1084 sub fleshed_circ_retrieve {
1085         my( $self, $client, $id ) = @_;
1086         my $e = new_editor();
1087         my $circ = $e->retrieve_action_circulation(
1088                 [
1089                         $id,
1090                         { 
1091                                 flesh                           => 4,
1092                                 flesh_fields    => { 
1093                                         circ => [ qw/ target_copy / ],
1094                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1095                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1096                                         acn => [ qw/ record / ],
1097                                 }
1098                         }
1099                 ]
1100         ) or return $e->event;
1101         
1102         my $copy = $circ->target_copy;
1103         my $vol = $copy->call_number;
1104         my $rec = $circ->target_copy->call_number->record;
1105
1106         $vol->record($rec->id);
1107         $copy->call_number($vol->id);
1108         $circ->target_copy($copy->id);
1109
1110         my $mvr;
1111
1112         if( $rec->id == OILS_PRECAT_RECORD ) {
1113                 $rec = undef;
1114                 $vol = undef;
1115         } else { 
1116                 $mvr = $U->record_to_mvr($rec);
1117                 $rec->marc(''); # drop the bulky marc data
1118         }
1119
1120         return {
1121                 circ => $circ,
1122                 copy => $copy,
1123                 volume => $vol,
1124                 record => $rec,
1125                 mvr => $mvr,
1126         };
1127 }
1128
1129
1130
1131 __PACKAGE__->register_method(
1132         method  => "test_batch_circ_events",
1133         api_name        => "open-ils.circ.trigger_event_by_def_and_barcode.fire"
1134 );
1135
1136 #  method for testing the behavior of a given event definition
1137 sub test_batch_circ_events {
1138     my($self, $conn, $auth, $event_def, $barcode) = @_;
1139
1140     my $e = new_editor(authtoken => $auth);
1141         return $e->event unless $e->checkauth;
1142     return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1143
1144     my $copy = $e->search_asset_copy({barcode => $barcode, deleted => 'f'})->[0]
1145         or return $e->event;
1146
1147     my $circ = $e->search_action_circulation(
1148         {target_copy => $copy->id, checkin_time => undef})->[0]
1149         or return $e->event;
1150         
1151     return undef unless $circ;
1152
1153     return $U->fire_object_event($event_def, undef, $circ, $e->requestor->ws_ou)
1154 }
1155
1156
1157
1158
1159 # {"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}}
1160
1161
1162 1;