]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
fixed faulty date query on user transaction search, updated some docs, update API...
[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 => {circ => ['checkin_workstation']},
852                 order_by => { circ => 'xact_start desc' }, 
853                 limit => 1 
854             }
855                 ]
856         )->[0];
857
858
859         return {
860                 copy            => $copy,
861                 hold            => $hold,
862                 transit => $transit,
863                 circ            => $circ,
864                 volume  => $vol,
865                 mvr             => $mvr,
866         };
867 }
868
869
870
871
872 __PACKAGE__->register_method(
873         method => 'mark_item',
874         api_name => 'open-ils.circ.mark_item_damaged',
875         signature       => q/
876                 Changes the status of a copy to "damaged". Requires MARK_ITEM_DAMAGED permission.
877                 @param authtoken The login session key
878                 @param copy_id The ID of the copy to mark as damaged
879                 @return 1 on success - Event otherwise.
880                 /
881 );
882 __PACKAGE__->register_method(
883         method => 'mark_item',
884         api_name => 'open-ils.circ.mark_item_missing',
885         signature       => q/
886                 Changes the status of a copy to "missing". Requires MARK_ITEM_MISSING permission.
887                 @param authtoken The login session key
888                 @param copy_id The ID of the copy to mark as missing 
889                 @return 1 on success - Event otherwise.
890                 /
891 );
892 __PACKAGE__->register_method(
893         method => 'mark_item',
894         api_name => 'open-ils.circ.mark_item_bindery',
895         signature       => q/
896                 Changes the status of a copy to "bindery". Requires MARK_ITEM_BINDERY permission.
897                 @param authtoken The login session key
898                 @param copy_id The ID of the copy to mark as bindery
899                 @return 1 on success - Event otherwise.
900                 /
901 );
902 __PACKAGE__->register_method(
903         method => 'mark_item',
904         api_name => 'open-ils.circ.mark_item_on_order',
905         signature       => q/
906                 Changes the status of a copy to "on order". Requires MARK_ITEM_ON_ORDER permission.
907                 @param authtoken The login session key
908                 @param copy_id The ID of the copy to mark as on order 
909                 @return 1 on success - Event otherwise.
910                 /
911 );
912 __PACKAGE__->register_method(
913         method => 'mark_item',
914         api_name => 'open-ils.circ.mark_item_ill',
915         signature       => q/
916                 Changes the status of a copy to "inter-library loan". Requires MARK_ITEM_ILL permission.
917                 @param authtoken The login session key
918                 @param copy_id The ID of the copy to mark as inter-library loan
919                 @return 1 on success - Event otherwise.
920                 /
921 );
922 __PACKAGE__->register_method(
923         method => 'mark_item',
924         api_name => 'open-ils.circ.mark_item_cataloging',
925         signature       => q/
926                 Changes the status of a copy to "cataloging". Requires MARK_ITEM_CATALOGING permission.
927                 @param authtoken The login session key
928                 @param copy_id The ID of the copy to mark as cataloging 
929                 @return 1 on success - Event otherwise.
930                 /
931 );
932 __PACKAGE__->register_method(
933         method => 'mark_item',
934         api_name => 'open-ils.circ.mark_item_reserves',
935         signature       => q/
936                 Changes the status of a copy to "reserves". Requires MARK_ITEM_RESERVES permission.
937                 @param authtoken The login session key
938                 @param copy_id The ID of the copy to mark as reserves
939                 @return 1 on success - Event otherwise.
940                 /
941 );
942 __PACKAGE__->register_method(
943         method => 'mark_item',
944         api_name => 'open-ils.circ.mark_item_discard',
945         signature       => q/
946                 Changes the status of a copy to "discard". Requires MARK_ITEM_DISCARD permission.
947                 @param authtoken The login session key
948                 @param copy_id The ID of the copy to mark as discard
949                 @return 1 on success - Event otherwise.
950                 /
951 );
952
953 sub mark_item {
954         my( $self, $conn, $auth, $copy_id, $args ) = @_;
955         my $e = new_editor(authtoken=>$auth, xact =>1);
956         return $e->die_event unless $e->checkauth;
957     $args ||= {};
958
959     my $copy = $e->retrieve_asset_copy([
960         $copy_id,
961         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
962             or return $e->die_event;
963
964     my $owning_lib = 
965         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
966             $copy->circ_lib : $copy->call_number->owning_lib;
967
968     return $e->die_event unless $e->allowed('UPDATE_COPY', $owning_lib);
969
970
971         my $perm = 'MARK_ITEM_MISSING';
972         my $stat = OILS_COPY_STATUS_MISSING;
973
974         if( $self->api_name =~ /damaged/ ) {
975                 $perm = 'MARK_ITEM_DAMAGED';
976                 $stat = OILS_COPY_STATUS_DAMAGED;
977         my $evt = handle_mark_damaged($e, $copy, $owning_lib, $args);
978         return $evt if $evt;
979
980         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
981         $ses->request('open-ils.trigger.event.autocreate', 'damaged', $copy, $owning_lib);
982
983         } elsif ( $self->api_name =~ /bindery/ ) {
984                 $perm = 'MARK_ITEM_BINDERY';
985                 $stat = OILS_COPY_STATUS_BINDERY;
986         } elsif ( $self->api_name =~ /on_order/ ) {
987                 $perm = 'MARK_ITEM_ON_ORDER';
988                 $stat = OILS_COPY_STATUS_ON_ORDER;
989         } elsif ( $self->api_name =~ /ill/ ) {
990                 $perm = 'MARK_ITEM_ILL';
991                 $stat = OILS_COPY_STATUS_ILL;
992         } elsif ( $self->api_name =~ /cataloging/ ) {
993                 $perm = 'MARK_ITEM_CATALOGING';
994                 $stat = OILS_COPY_STATUS_CATALOGING;
995         } elsif ( $self->api_name =~ /reserves/ ) {
996                 $perm = 'MARK_ITEM_RESERVES';
997                 $stat = OILS_COPY_STATUS_RESERVES;
998         } elsif ( $self->api_name =~ /discard/ ) {
999                 $perm = 'MARK_ITEM_DISCARD';
1000                 $stat = OILS_COPY_STATUS_DISCARD;
1001         }
1002
1003
1004         $copy->status($stat);
1005         $copy->edit_date('now');
1006         $copy->editor($e->requestor->id);
1007
1008         $e->update_asset_copy($copy) or return $e->die_event;
1009
1010         my $holds = $e->search_action_hold_request(
1011                 { 
1012                         current_copy => $copy->id,
1013                         fulfillment_time => undef,
1014                         cancel_time => undef,
1015                 }
1016         );
1017
1018         $e->commit;
1019
1020         $logger->debug("resetting holds that target the marked copy");
1021         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
1022
1023         return 1;
1024 }
1025
1026 sub handle_mark_damaged {
1027     my($e, $copy, $owning_lib, $args) = @_;
1028
1029     my $apply = $args->{apply_fines} || '';
1030     return undef if $apply eq 'noapply';
1031
1032     # grab the last circulation
1033     my $circ = $e->search_action_circulation([
1034         {   target_copy => $copy->id}, 
1035         {   limit => 1, 
1036             order_by => {circ => "xact_start DESC"},
1037             flesh => 2,
1038             flesh_fields => {circ => ['target_copy', 'usr'], au => ['card']}
1039         }
1040     ])->[0];
1041
1042     return undef unless $circ;
1043
1044     my $charge_price = $U->ou_ancestor_setting_value(
1045         $owning_lib, 'circ.charge_on_damaged', $e);
1046
1047     my $proc_fee = $U->ou_ancestor_setting_value(
1048         $owning_lib, 'circ.damaged_item_processing_fee', $e) || 0;
1049
1050     return undef unless $charge_price or $proc_fee;
1051
1052     my $copy_price = ($charge_price) ? $U->get_copy_price($e, $copy) : 0;
1053     my $total = $copy_price + $proc_fee;
1054
1055     if($apply) {
1056         
1057         if($charge_price and $copy_price) {
1058             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1059                 $e, $copy_price, 7, 'Damaged Item', $circ->id);
1060             return $evt if $evt;
1061         }
1062
1063         if($proc_fee) {
1064             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1065                 $e, $proc_fee, 8, 'Damaged Item Processing Fee', $circ->id);
1066             return $evt if $evt;
1067         }
1068
1069         my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
1070         return $evt if $evt;
1071
1072         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1073         $ses->request('open-ils.trigger.event.autocreate', 'checkout.damaged', $circ, $circ->circ_lib);
1074
1075         return undef;
1076
1077     } else {
1078         return OpenILS::Event->new('DAMAGE_CHARGE', 
1079             payload => {
1080                 circ => $circ,
1081                 charge => $total
1082             }
1083         );
1084     }
1085 }
1086
1087
1088
1089
1090
1091
1092 # ----------------------------------------------------------------------
1093 __PACKAGE__->register_method(
1094         method => 'magic_fetch',
1095         api_name => 'open-ils.agent.fetch'
1096 );
1097
1098 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
1099
1100 sub magic_fetch {
1101         my( $self, $conn, $auth, $args ) = @_;
1102         my $e = new_editor( authtoken => $auth );
1103         return $e->event unless $e->checkauth;
1104
1105         my $hint = $$args{hint};
1106         my $id  = $$args{id};
1107
1108         # Is the call allowed to fetch this type of object?
1109         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
1110
1111         # Find the class the implements the given hint
1112         my ($class) = grep { 
1113                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
1114
1115         $class =~ s/Fieldmapper:://og;
1116         $class =~ s/::/_/og;
1117         my $method = "retrieve_$class";
1118
1119         my $obj = $e->$method($id) or return $e->event;
1120         return $obj;
1121 }
1122 # ----------------------------------------------------------------------
1123
1124
1125 __PACKAGE__->register_method(
1126         method  => "fleshed_circ_retrieve",
1127     authoritative => 1,
1128         api_name        => "open-ils.circ.fleshed.retrieve",);
1129
1130 sub fleshed_circ_retrieve {
1131         my( $self, $client, $id ) = @_;
1132         my $e = new_editor();
1133         my $circ = $e->retrieve_action_circulation(
1134                 [
1135                         $id,
1136                         { 
1137                                 flesh                           => 4,
1138                                 flesh_fields    => { 
1139                                         circ => [ qw/ target_copy / ],
1140                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1141                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1142                                         acn => [ qw/ record / ],
1143                                 }
1144                         }
1145                 ]
1146         ) or return $e->event;
1147         
1148         my $copy = $circ->target_copy;
1149         my $vol = $copy->call_number;
1150         my $rec = $circ->target_copy->call_number->record;
1151
1152         $vol->record($rec->id);
1153         $copy->call_number($vol->id);
1154         $circ->target_copy($copy->id);
1155
1156         my $mvr;
1157
1158         if( $rec->id == OILS_PRECAT_RECORD ) {
1159                 $rec = undef;
1160                 $vol = undef;
1161         } else { 
1162                 $mvr = $U->record_to_mvr($rec);
1163                 $rec->marc(''); # drop the bulky marc data
1164         }
1165
1166         return {
1167                 circ => $circ,
1168                 copy => $copy,
1169                 volume => $vol,
1170                 record => $rec,
1171                 mvr => $mvr,
1172         };
1173 }
1174
1175
1176
1177 __PACKAGE__->register_method(
1178         method  => "test_batch_circ_events",
1179         api_name        => "open-ils.circ.trigger_event_by_def_and_barcode.fire"
1180 );
1181
1182 #  method for testing the behavior of a given event definition
1183 sub test_batch_circ_events {
1184     my($self, $conn, $auth, $event_def, $barcode) = @_;
1185
1186     my $e = new_editor(authtoken => $auth);
1187         return $e->event unless $e->checkauth;
1188     return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1189
1190     my $copy = $e->search_asset_copy({barcode => $barcode, deleted => 'f'})->[0]
1191         or return $e->event;
1192
1193     my $circ = $e->search_action_circulation(
1194         {target_copy => $copy->id, checkin_time => undef})->[0]
1195         or return $e->event;
1196         
1197     return undef unless $circ;
1198
1199     return $U->fire_object_event($event_def, undef, $circ, $e->requestor->ws_ou)
1200 }
1201
1202
1203
1204 __PACKAGE__->register_method(
1205         method  => "user_payments_list",
1206         api_name        => "open-ils.circ.user_payments.filtered.batch",
1207     stream => 1,
1208         signature => {
1209         desc => q/Returns a fleshed, date-limited set of all payments a user
1210                 has made.  By default, ordered by payment date.  Optionally
1211                 ordered by other columns in the top-level "mp" object/,
1212         params => [
1213             {desc => 'Authentication token', type => 'string'},
1214             {desc => 'User ID', type => 'number'},
1215             {desc => 'Order by column(s), optional.  Array of "mp" class columns', type => 'array'}
1216         ],
1217         return => {desc => q/List of "mp" objects, fleshed with the billable transaction 
1218             and the related fully-realized payment object (e.g money.cash_payment)/}
1219     }
1220 );
1221
1222 sub user_payments_list {
1223     my($self, $conn, $auth, $user_id, $start_date, $end_date, $order_by) = @_;
1224
1225     my $e = new_editor(authtoken => $auth);
1226     return $e->event unless $e->checkauth;
1227
1228     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1229     return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $user->home_ou);
1230
1231     $order_by ||= ['payment_ts'];
1232
1233     # all payments by user, between start_date and end_date
1234     my $payments = $e->json_query({
1235         select => {mp => ['id']}, 
1236         from => {
1237             mp => {
1238                 mbt => {
1239                     fkey => 'xact', field => 'id'}
1240             }
1241         }, 
1242         where => {
1243             '+mbt' => {usr => $user_id}, 
1244             '+mp' => {payment_ts => {between => [$start_date, $end_date]}}
1245         },
1246         order_by => {mp => $order_by}
1247     });
1248
1249     for my $payment_id (@$payments) {
1250         my $payment = $e->retrieve_money_payment([
1251             $payment_id->{id}, 
1252             {   
1253                 flesh => 2,
1254                 flesh_fields => {
1255                     mp => [
1256                         'xact',
1257                         'cash_payment',
1258                         'credit_card_payment',
1259                         'credit_payment',
1260                         'check_payment',
1261                         'work_payment',
1262                         'forgive_payment',
1263                         'goods_payment'
1264                     ],
1265                     mbt => [
1266                         'circulation', 
1267                         'grocery'
1268                     ]
1269                 }
1270             }
1271         ]);
1272         $conn->respond($payment);
1273     }
1274
1275     return undef;
1276 }
1277
1278
1279 # {"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}}
1280
1281
1282 1;