]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
added a batch version of the post-checkin backdate call: open-ils.circ.post_checkin_b...
[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 __PACKAGE__->register_method(
379         method  => "post_checkin_backdate_circ",
380         api_name        => "open-ils.circ.post_checkin_backdate.batch",
381     stream => 1,
382         signature => {
383         desc => q/@see open-ils.circ.post_checkin_backdate.  Batch mode/,
384         params => [
385             {desc => 'Authentication token', type => 'string'},
386             {desc => 'List of Circ ID', type => 'array'},
387             {desc => 'ISO8601 backdate', type => 'string'},
388         ],
389         return => {desc => q/Set of: 1 on success, failure event on error/}
390     }
391 );
392
393
394 sub post_checkin_backdate_circ {
395     my( $self, $conn, $auth, $circ_id, $backdate ) = @_;
396     my $e = new_editor(authtoken=>$auth);
397     return $e->die_event unless $e->checkauth;
398     if($self->api_name =~ /batch/) {
399         $conn->respond(post_checkin_backdate_circ_impl($e, $_, $backdate)) for $circ_id;
400     } else {
401         $conn->respond_complete(post_checkin_backdate_circ_impl($e, $circ_id, $backdate));
402     }
403
404     $e->disconnect;
405     return undef;
406 }
407
408
409 sub post_checkin_backdate_circ_impl {
410     my($e, $circ_id, $backdate) = @_;
411
412     $e->xact_begin;
413
414     my $circ = $e->retrieve_action_circulation($circ_id)
415         or return $e->die_event;
416
417     # anyone with checkin perms can backdate (more restrictive?)
418     return $e->die_event unless $e->allowed('COPY_CHECKIN', $circ->circ_lib);
419
420     # don't allow back-dating an open circulation
421     return OpenILS::Event->new('BAD_PARAMS') unless 
422         $backdate and $circ->checkin_time;
423
424     # update the checkin and stop_fines times to reflect the new backdate
425     $circ->stop_fines_time(clense_ISO8601($backdate));
426     $circ->checkin_time(clense_ISO8601($backdate));
427     $e->update_action_circulation($circ) or return $e->die_event;
428
429     # now void the overdues "erased" by the back-dating
430     my $evt = OpenILS::Application::Circ::CircCommon->void_overdues($e, $circ, $backdate);
431     return $evt if $evt;
432
433     # If the circ was closed before and the balance owned !=0, re-open the transaction
434     $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
435     return $evt if $evt;
436
437     $e->xact_commit;
438     return 1;
439 }
440
441
442
443 __PACKAGE__->register_method (
444         method          => 'set_circ_due_date',
445         api_name                => 'open-ils.circ.circulation.due_date.update',
446         signature       => q/
447                 Updates the due_date on the given circ
448                 @param authtoken
449                 @param circid The id of the circ to update
450                 @param date The timestamp of the new due date
451         /
452 );
453
454 sub set_circ_due_date {
455         my( $self, $conn, $auth, $circ_id, $date ) = @_;
456
457     my $e = new_editor(xact=>1, authtoken=>$auth);
458     return $e->die_event unless $e->checkauth;
459     my $circ = $e->retrieve_action_circulation($circ_id)
460         or return $e->die_event;
461
462     return $e->die_event unless $e->allowed('CIRC_OVERRIDE_DUE_DATE', $circ->circ_lib);
463         $date = clense_ISO8601($date);
464         $circ->due_date($date);
465     $e->update_action_circulation($circ) or return $e->die_event;
466     $e->commit;
467
468     return $circ->id;
469 }
470
471
472 __PACKAGE__->register_method(
473         method          => "create_in_house_use",
474         api_name                => 'open-ils.circ.in_house_use.create',
475         signature       =>      q/
476                 Creates an in-house use action.
477                 @param $authtoken The login session key
478                 @param params A hash of params including
479                         'location' The org unit id where the in-house use occurs
480                         'copyid' The copy in question
481                         'count' The number of in-house uses to apply to this copy
482                 @return An array of id's representing the id's of the newly created
483                 in-house use objects or an event on an error
484         /);
485
486 __PACKAGE__->register_method(
487         method          => "create_in_house_use",
488         api_name                => 'open-ils.circ.non_cat_in_house_use.create',
489 );
490
491
492 sub create_in_house_use {
493         my( $self, $client, $auth, $params ) = @_;
494
495         my( $evt, $copy );
496         my $org                 = $params->{location};
497         my $copyid              = $params->{copyid};
498         my $count               = $params->{count} || 1;
499         my $nc_type             = $params->{non_cat_type};
500         my $use_time    = $params->{use_time} || 'now';
501
502         my $e = new_editor(xact=>1,authtoken=>$auth);
503         return $e->event unless $e->checkauth;
504         return $e->event unless $e->allowed('CREATE_IN_HOUSE_USE');
505
506         my $non_cat = 1 if $self->api_name =~ /non_cat/;
507
508         unless( $non_cat ) {
509                 if( $copyid ) {
510                         $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
511                 } else {
512                         $copy = $e->search_asset_copy({barcode=>$params->{barcode}, deleted => 'f'})->[0]
513                                 or return $e->event;
514                         $copyid = $copy->id;
515                 }
516         }
517
518         if( $use_time ne 'now' ) {
519                 $use_time = clense_ISO8601($use_time);
520                 $logger->debug("in_house_use setting use time to $use_time");
521         }
522
523         my @ids;
524         for(1..$count) {
525
526                 my $ihu;
527                 my $method;
528                 my $cmeth;
529
530                 if($non_cat) {
531                         $ihu = Fieldmapper::action::non_cat_in_house_use->new;
532                         $ihu->item_type($nc_type);
533                         $method = 'open-ils.storage.direct.action.non_cat_in_house_use.create';
534                         $cmeth = "create_action_non_cat_in_house_use";
535
536                 } else {
537                         $ihu = Fieldmapper::action::in_house_use->new;
538                         $ihu->item($copyid);
539                         $method = 'open-ils.storage.direct.action.in_house_use.create';
540                         $cmeth = "create_action_in_house_use";
541                 }
542
543                 $ihu->staff($e->requestor->id);
544                 $ihu->org_unit($org);
545                 $ihu->use_time($use_time);
546
547                 $ihu = $e->$cmeth($ihu) or return $e->event;
548                 push( @ids, $ihu->id );
549         }
550
551         $e->commit;
552         return \@ids;
553 }
554
555
556
557
558
559 __PACKAGE__->register_method(
560         method  => "view_circs",
561         api_name        => "open-ils.circ.copy_checkout_history.retrieve",
562         notes           => q/
563                 Retrieves the last X circs for a given copy
564                 @param authtoken The login session key
565                 @param copyid The copy to check
566                 @param count How far to go back in the item history
567                 @return An array of circ ids
568         /);
569
570 # ----------------------------------------------------------------------
571 # Returns $count most recent circs.  If count exceeds the configured 
572 # max, use the configured max instead
573 # ----------------------------------------------------------------------
574 sub view_circs {
575         my( $self, $client, $authtoken, $copyid, $count ) = @_; 
576
577     my $e = new_editor(authtoken => $authtoken);
578     return $e->event unless $e->checkauth;
579     
580     my $copy = $e->retrieve_asset_copy([
581         $copyid,
582         {   flesh => 1,
583             flesh_fields => {acp => ['call_number']}
584         }
585     ]) or return $e->event;
586
587     return $e->event unless $e->allowed(
588         'VIEW_COPY_CHECKOUT_HISTORY', 
589         ($copy->call_number == OILS_PRECAT_CALL_NUMBER) ? 
590             $copy->circ_lib : $copy->call_number->owning_lib);
591         
592     my $max_history = $U->ou_ancestor_setting_value(
593         $e->requestor->ws_ou, 'circ.item_checkout_history.max', $e);
594
595     if(defined $max_history) {
596         $count = $max_history unless defined $count and $count < $max_history;
597     } else {
598         $count = 4 unless defined $count;
599     }
600
601     return $e->search_action_circulation([
602         {target_copy => $copyid}, 
603         {limit => $count, order_by => { circ => "xact_start DESC" }} 
604     ]);
605 }
606
607
608 __PACKAGE__->register_method(
609         method  => "circ_count",
610         api_name        => "open-ils.circ.circulation.count",
611         notes           => q/
612                 Returns the number of times the item has circulated
613                 @param copyid The copy to check
614         /);
615
616 sub circ_count {
617         my( $self, $client, $copyid, $range ) = @_; 
618         my $e = OpenILS::Utils::Editor->new;
619         return $e->request('open-ils.storage.asset.copy.circ_count', $copyid, $range);
620 }
621
622
623
624 __PACKAGE__->register_method(
625         method          => 'fetch_notes',
626         api_name                => 'open-ils.circ.copy_note.retrieve.all',
627         signature       => q/
628                 Returns an array of copy note objects.  
629                 @param args A named hash of parameters including:
630                         authtoken       : Required if viewing non-public notes
631                         itemid          : The id of the item whose notes we want to retrieve
632                         pub                     : True if all the caller wants are public notes
633                 @return An array of note objects
634         /);
635
636 __PACKAGE__->register_method(
637         method          => 'fetch_notes',
638         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
639         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
640
641 __PACKAGE__->register_method(
642         method          => 'fetch_notes',
643         api_name                => 'open-ils.circ.title_note.retrieve.all',
644         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
645
646
647 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
648 sub fetch_notes {
649         my( $self, $connection, $args ) = @_;
650
651         my $id = $$args{itemid};
652         my $authtoken = $$args{authtoken};
653         my( $r, $evt);
654
655         if( $self->api_name =~ /copy/ ) {
656                 if( $$args{pub} ) {
657                         return $U->cstorereq(
658                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
659                                 { owning_copy => $id, pub => 't' } );
660                 } else {
661                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
662                         return $evt if $evt;
663                         return $U->cstorereq(
664                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
665                 }
666
667         } elsif( $self->api_name =~ /call_number/ ) {
668                 if( $$args{pub} ) {
669                         return $U->cstorereq(
670                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
671                                 { call_number => $id, pub => 't' } );
672                 } else {
673                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
674                         return $evt if $evt;
675                         return $U->cstorereq(
676                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
677                 }
678
679         } elsif( $self->api_name =~ /title/ ) {
680                 if( $$args{pub} ) {
681                         return $U->cstorereq(
682                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
683                                 { record => $id, pub => 't' } );
684                 } else {
685                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
686                         return $evt if $evt;
687                         return $U->cstorereq(
688                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
689                 }
690         }
691
692         return undef;
693 }
694
695 __PACKAGE__->register_method(
696         method  => 'has_notes',
697         api_name        => 'open-ils.circ.copy.has_notes');
698 __PACKAGE__->register_method(
699         method  => 'has_notes',
700         api_name        => 'open-ils.circ.call_number.has_notes');
701 __PACKAGE__->register_method(
702         method  => 'has_notes',
703         api_name        => 'open-ils.circ.title.has_notes');
704
705
706 sub has_notes {
707         my( $self, $conn, $authtoken, $id ) = @_;
708         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
709         return $editor->event unless $editor->checkauth;
710
711         my $n = $editor->search_asset_copy_note(
712                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
713
714         $n = $editor->search_asset_call_number_note(
715                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
716
717         $n = $editor->search_biblio_record_note(
718                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
719
720         return scalar @$n;
721 }
722
723
724
725 __PACKAGE__->register_method(
726         method          => 'create_copy_note',
727         api_name                => 'open-ils.circ.copy_note.create',
728         signature       => q/
729                 Creates a new copy note
730                 @param authtoken The login session key
731                 @param note     The note object to create
732                 @return The id of the new note object
733         /);
734
735 sub create_copy_note {
736         my( $self, $connection, $authtoken, $note ) = @_;
737
738         my $e = new_editor(xact=>1, authtoken=>$authtoken);
739         return $e->event unless $e->checkauth;
740         my $copy = $e->retrieve_asset_copy(
741                 [
742                         $note->owning_copy,
743                         {       flesh => 1,
744                                 flesh_fields => { 'acp' => ['call_number'] }
745                         }
746                 ]
747         );
748
749         return $e->event unless 
750                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
751
752         $note->create_date('now');
753         $note->creator($e->requestor->id);
754         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
755         $note->clear_id;
756
757         $e->create_asset_copy_note($note) or return $e->event;
758         $e->commit;
759         return $note->id;
760 }
761
762
763 __PACKAGE__->register_method(
764         method          => 'delete_copy_note',
765         api_name                =>      'open-ils.circ.copy_note.delete',
766         signature       => q/
767                 Deletes an existing copy note
768                 @param authtoken The login session key
769                 @param noteid The id of the note to delete
770                 @return 1 on success - Event otherwise.
771                 /);
772 sub delete_copy_note {
773         my( $self, $conn, $authtoken, $noteid ) = @_;
774
775         my $e = new_editor(xact=>1, authtoken=>$authtoken);
776         return $e->die_event unless $e->checkauth;
777
778         my $note = $e->retrieve_asset_copy_note([
779                 $noteid,
780                 { flesh => 2,
781                         flesh_fields => {
782                                 'acpn' => [ 'owning_copy' ],
783                                 'acp' => [ 'call_number' ],
784                         }
785                 }
786         ]) or return $e->die_event;
787
788         if( $note->creator ne $e->requestor->id ) {
789                 return $e->die_event unless 
790                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
791         }
792
793         $e->delete_asset_copy_note($note) or return $e->die_event;
794         $e->commit;
795         return 1;
796 }
797
798
799 __PACKAGE__->register_method(
800         method => 'age_hold_rules',
801         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
802 );
803
804 sub age_hold_rules {
805         my( $self, $conn ) = @_;
806         return new_editor()->retrieve_all_config_rules_age_hold_protect();
807 }
808
809
810
811 __PACKAGE__->register_method(
812         method => 'copy_details_barcode',
813     authoritative => 1,
814         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
815 sub copy_details_barcode {
816         my( $self, $conn, $auth, $barcode ) = @_;
817     my $e = new_editor();
818     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
819     return $e->event unless $cid;
820         return copy_details( $self, $conn, $auth, $cid );
821 }
822
823
824 __PACKAGE__->register_method(
825         method => 'copy_details',
826         api_name => 'open-ils.circ.copy_details.retrieve');
827
828 sub copy_details {
829         my( $self, $conn, $auth, $copy_id ) = @_;
830         my $e = new_editor(authtoken=>$auth);
831         return $e->event unless $e->checkauth;
832
833         my $flesh = { flesh => 1 };
834
835         my $copy = $e->retrieve_asset_copy(
836                 [
837                         $copy_id,
838                         {
839                                 flesh => 2,
840                                 flesh_fields => {
841                                         acp => ['call_number'],
842                                         acn => ['record']
843                                 }
844                         }
845                 ]) or return $e->event;
846
847
848         # De-flesh the copy for backwards compatibility
849         my $mvr;
850         my $vol = $copy->call_number;
851         if( ref $vol ) {
852                 $copy->call_number($vol->id);
853                 my $record = $vol->record;
854                 if( ref $record ) {
855                         $vol->record($record->id);
856                         $mvr = $U->record_to_mvr($record);
857                 }
858         }
859
860
861         my $hold = $e->search_action_hold_request(
862                 { 
863                         current_copy            => $copy_id, 
864                         capture_time            => { "!=" => undef },
865                         fulfillment_time        => undef,
866                         cancel_time                     => undef,
867                 }
868         )->[0];
869
870         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
871
872         my $transit = $e->search_action_transit_copy(
873                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
874
875         # find the latest circ, open or closed
876         my $circ = $e->search_action_circulation(
877                 [
878                         { target_copy => $copy_id },
879                         { 
880                 flesh => 1,
881                 flesh_fields => {
882                     circ => [
883                         'checkin_workstation', 
884                         'duration_rule', 
885                         'max_fine_rule', 
886                         'recuring_fine_rule'
887                     ]
888                 },
889                 order_by => { circ => 'xact_start desc' }, 
890                 limit => 1 
891             }
892                 ]
893         )->[0];
894
895
896         return {
897                 copy            => $copy,
898                 hold            => $hold,
899                 transit => $transit,
900                 circ            => $circ,
901                 volume  => $vol,
902                 mvr             => $mvr,
903         };
904 }
905
906
907
908
909 __PACKAGE__->register_method(
910         method => 'mark_item',
911         api_name => 'open-ils.circ.mark_item_damaged',
912         signature       => q/
913                 Changes the status of a copy to "damaged". Requires MARK_ITEM_DAMAGED permission.
914                 @param authtoken The login session key
915                 @param copy_id The ID of the copy to mark as damaged
916                 @return 1 on success - Event otherwise.
917                 /
918 );
919 __PACKAGE__->register_method(
920         method => 'mark_item',
921         api_name => 'open-ils.circ.mark_item_missing',
922         signature       => q/
923                 Changes the status of a copy to "missing". Requires MARK_ITEM_MISSING permission.
924                 @param authtoken The login session key
925                 @param copy_id The ID of the copy to mark as missing 
926                 @return 1 on success - Event otherwise.
927                 /
928 );
929 __PACKAGE__->register_method(
930         method => 'mark_item',
931         api_name => 'open-ils.circ.mark_item_bindery',
932         signature       => q/
933                 Changes the status of a copy to "bindery". Requires MARK_ITEM_BINDERY permission.
934                 @param authtoken The login session key
935                 @param copy_id The ID of the copy to mark as bindery
936                 @return 1 on success - Event otherwise.
937                 /
938 );
939 __PACKAGE__->register_method(
940         method => 'mark_item',
941         api_name => 'open-ils.circ.mark_item_on_order',
942         signature       => q/
943                 Changes the status of a copy to "on order". Requires MARK_ITEM_ON_ORDER permission.
944                 @param authtoken The login session key
945                 @param copy_id The ID of the copy to mark as on order 
946                 @return 1 on success - Event otherwise.
947                 /
948 );
949 __PACKAGE__->register_method(
950         method => 'mark_item',
951         api_name => 'open-ils.circ.mark_item_ill',
952         signature       => q/
953                 Changes the status of a copy to "inter-library loan". Requires MARK_ITEM_ILL permission.
954                 @param authtoken The login session key
955                 @param copy_id The ID of the copy to mark as inter-library loan
956                 @return 1 on success - Event otherwise.
957                 /
958 );
959 __PACKAGE__->register_method(
960         method => 'mark_item',
961         api_name => 'open-ils.circ.mark_item_cataloging',
962         signature       => q/
963                 Changes the status of a copy to "cataloging". Requires MARK_ITEM_CATALOGING permission.
964                 @param authtoken The login session key
965                 @param copy_id The ID of the copy to mark as cataloging 
966                 @return 1 on success - Event otherwise.
967                 /
968 );
969 __PACKAGE__->register_method(
970         method => 'mark_item',
971         api_name => 'open-ils.circ.mark_item_reserves',
972         signature       => q/
973                 Changes the status of a copy to "reserves". Requires MARK_ITEM_RESERVES permission.
974                 @param authtoken The login session key
975                 @param copy_id The ID of the copy to mark as reserves
976                 @return 1 on success - Event otherwise.
977                 /
978 );
979 __PACKAGE__->register_method(
980         method => 'mark_item',
981         api_name => 'open-ils.circ.mark_item_discard',
982         signature       => q/
983                 Changes the status of a copy to "discard". Requires MARK_ITEM_DISCARD permission.
984                 @param authtoken The login session key
985                 @param copy_id The ID of the copy to mark as discard
986                 @return 1 on success - Event otherwise.
987                 /
988 );
989
990 sub mark_item {
991         my( $self, $conn, $auth, $copy_id, $args ) = @_;
992         my $e = new_editor(authtoken=>$auth, xact =>1);
993         return $e->die_event unless $e->checkauth;
994     $args ||= {};
995
996     my $copy = $e->retrieve_asset_copy([
997         $copy_id,
998         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])
999             or return $e->die_event;
1000
1001     my $owning_lib = 
1002         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
1003             $copy->circ_lib : $copy->call_number->owning_lib;
1004
1005     return $e->die_event unless $e->allowed('UPDATE_COPY', $owning_lib);
1006
1007
1008         my $perm = 'MARK_ITEM_MISSING';
1009         my $stat = OILS_COPY_STATUS_MISSING;
1010
1011         if( $self->api_name =~ /damaged/ ) {
1012                 $perm = 'MARK_ITEM_DAMAGED';
1013                 $stat = OILS_COPY_STATUS_DAMAGED;
1014         my $evt = handle_mark_damaged($e, $copy, $owning_lib, $args);
1015         return $evt if $evt;
1016
1017         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1018         $ses->request('open-ils.trigger.event.autocreate', 'damaged', $copy, $owning_lib);
1019
1020         } elsif ( $self->api_name =~ /bindery/ ) {
1021                 $perm = 'MARK_ITEM_BINDERY';
1022                 $stat = OILS_COPY_STATUS_BINDERY;
1023         } elsif ( $self->api_name =~ /on_order/ ) {
1024                 $perm = 'MARK_ITEM_ON_ORDER';
1025                 $stat = OILS_COPY_STATUS_ON_ORDER;
1026         } elsif ( $self->api_name =~ /ill/ ) {
1027                 $perm = 'MARK_ITEM_ILL';
1028                 $stat = OILS_COPY_STATUS_ILL;
1029         } elsif ( $self->api_name =~ /cataloging/ ) {
1030                 $perm = 'MARK_ITEM_CATALOGING';
1031                 $stat = OILS_COPY_STATUS_CATALOGING;
1032         } elsif ( $self->api_name =~ /reserves/ ) {
1033                 $perm = 'MARK_ITEM_RESERVES';
1034                 $stat = OILS_COPY_STATUS_RESERVES;
1035         } elsif ( $self->api_name =~ /discard/ ) {
1036                 $perm = 'MARK_ITEM_DISCARD';
1037                 $stat = OILS_COPY_STATUS_DISCARD;
1038         }
1039
1040
1041         $copy->status($stat);
1042         $copy->edit_date('now');
1043         $copy->editor($e->requestor->id);
1044
1045         $e->update_asset_copy($copy) or return $e->die_event;
1046
1047         my $holds = $e->search_action_hold_request(
1048                 { 
1049                         current_copy => $copy->id,
1050                         fulfillment_time => undef,
1051                         cancel_time => undef,
1052                 }
1053         );
1054
1055         $e->commit;
1056
1057         $logger->debug("resetting holds that target the marked copy");
1058         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
1059
1060         return 1;
1061 }
1062
1063 sub handle_mark_damaged {
1064     my($e, $copy, $owning_lib, $args) = @_;
1065
1066     my $apply = $args->{apply_fines} || '';
1067     return undef if $apply eq 'noapply';
1068
1069     # grab the last circulation
1070     my $circ = $e->search_action_circulation([
1071         {   target_copy => $copy->id}, 
1072         {   limit => 1, 
1073             order_by => {circ => "xact_start DESC"},
1074             flesh => 2,
1075             flesh_fields => {circ => ['target_copy', 'usr'], au => ['card']}
1076         }
1077     ])->[0];
1078
1079     return undef unless $circ;
1080
1081     my $charge_price = $U->ou_ancestor_setting_value(
1082         $owning_lib, 'circ.charge_on_damaged', $e);
1083
1084     my $proc_fee = $U->ou_ancestor_setting_value(
1085         $owning_lib, 'circ.damaged_item_processing_fee', $e) || 0;
1086
1087     return undef unless $charge_price or $proc_fee;
1088
1089     my $copy_price = ($charge_price) ? $U->get_copy_price($e, $copy) : 0;
1090     my $total = $copy_price + $proc_fee;
1091
1092     if($apply) {
1093         
1094         if($charge_price and $copy_price) {
1095             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1096                 $e, $copy_price, 7, 'Damaged Item', $circ->id);
1097             return $evt if $evt;
1098         }
1099
1100         if($proc_fee) {
1101             my $evt = OpenILS::Application::Circ::CircCommon->create_bill(
1102                 $e, $proc_fee, 8, 'Damaged Item Processing Fee', $circ->id);
1103             return $evt if $evt;
1104         }
1105
1106         my $evt = OpenILS::Application::Circ::CircCommon->reopen_xact($e, $circ->id);
1107         return $evt if $evt;
1108
1109         my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1110         $ses->request('open-ils.trigger.event.autocreate', 'checkout.damaged', $circ, $circ->circ_lib);
1111
1112         return undef;
1113
1114     } else {
1115         return OpenILS::Event->new('DAMAGE_CHARGE', 
1116             payload => {
1117                 circ => $circ,
1118                 charge => $total
1119             }
1120         );
1121     }
1122 }
1123
1124
1125
1126
1127
1128
1129 # ----------------------------------------------------------------------
1130 __PACKAGE__->register_method(
1131         method => 'magic_fetch',
1132         api_name => 'open-ils.agent.fetch'
1133 );
1134
1135 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
1136
1137 sub magic_fetch {
1138         my( $self, $conn, $auth, $args ) = @_;
1139         my $e = new_editor( authtoken => $auth );
1140         return $e->event unless $e->checkauth;
1141
1142         my $hint = $$args{hint};
1143         my $id  = $$args{id};
1144
1145         # Is the call allowed to fetch this type of object?
1146         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
1147
1148         # Find the class the implements the given hint
1149         my ($class) = grep { 
1150                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
1151
1152         $class =~ s/Fieldmapper:://og;
1153         $class =~ s/::/_/og;
1154         my $method = "retrieve_$class";
1155
1156         my $obj = $e->$method($id) or return $e->event;
1157         return $obj;
1158 }
1159 # ----------------------------------------------------------------------
1160
1161
1162 __PACKAGE__->register_method(
1163         method  => "fleshed_circ_retrieve",
1164     authoritative => 1,
1165         api_name        => "open-ils.circ.fleshed.retrieve",);
1166
1167 sub fleshed_circ_retrieve {
1168         my( $self, $client, $id ) = @_;
1169         my $e = new_editor();
1170         my $circ = $e->retrieve_action_circulation(
1171                 [
1172                         $id,
1173                         { 
1174                                 flesh                           => 4,
1175                                 flesh_fields    => { 
1176                                         circ => [ qw/ target_copy / ],
1177                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1178                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1179                                         acn => [ qw/ record / ],
1180                                 }
1181                         }
1182                 ]
1183         ) or return $e->event;
1184         
1185         my $copy = $circ->target_copy;
1186         my $vol = $copy->call_number;
1187         my $rec = $circ->target_copy->call_number->record;
1188
1189         $vol->record($rec->id);
1190         $copy->call_number($vol->id);
1191         $circ->target_copy($copy->id);
1192
1193         my $mvr;
1194
1195         if( $rec->id == OILS_PRECAT_RECORD ) {
1196                 $rec = undef;
1197                 $vol = undef;
1198         } else { 
1199                 $mvr = $U->record_to_mvr($rec);
1200                 $rec->marc(''); # drop the bulky marc data
1201         }
1202
1203         return {
1204                 circ => $circ,
1205                 copy => $copy,
1206                 volume => $vol,
1207                 record => $rec,
1208                 mvr => $mvr,
1209         };
1210 }
1211
1212
1213
1214 __PACKAGE__->register_method(
1215         method  => "test_batch_circ_events",
1216         api_name        => "open-ils.circ.trigger_event_by_def_and_barcode.fire"
1217 );
1218
1219 #  method for testing the behavior of a given event definition
1220 sub test_batch_circ_events {
1221     my($self, $conn, $auth, $event_def, $barcode) = @_;
1222
1223     my $e = new_editor(authtoken => $auth);
1224         return $e->event unless $e->checkauth;
1225     return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
1226
1227     my $copy = $e->search_asset_copy({barcode => $barcode, deleted => 'f'})->[0]
1228         or return $e->event;
1229
1230     my $circ = $e->search_action_circulation(
1231         {target_copy => $copy->id, checkin_time => undef})->[0]
1232         or return $e->event;
1233         
1234     return undef unless $circ;
1235
1236     return $U->fire_object_event($event_def, undef, $circ, $e->requestor->ws_ou)
1237 }
1238
1239
1240
1241 __PACKAGE__->register_method(
1242         method  => "user_payments_list",
1243         api_name        => "open-ils.circ.user_payments.filtered.batch",
1244     stream => 1,
1245         signature => {
1246         desc => q/Returns a fleshed, date-limited set of all payments a user
1247                 has made.  By default, ordered by payment date.  Optionally
1248                 ordered by other columns in the top-level "mp" object/,
1249         params => [
1250             {desc => 'Authentication token', type => 'string'},
1251             {desc => 'User ID', type => 'number'},
1252             {desc => 'Order by column(s), optional.  Array of "mp" class columns', type => 'array'}
1253         ],
1254         return => {desc => q/List of "mp" objects, fleshed with the billable transaction 
1255             and the related fully-realized payment object (e.g money.cash_payment)/}
1256     }
1257 );
1258
1259 sub user_payments_list {
1260     my($self, $conn, $auth, $user_id, $start_date, $end_date, $order_by) = @_;
1261
1262     my $e = new_editor(authtoken => $auth);
1263     return $e->event unless $e->checkauth;
1264
1265     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1266     return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $user->home_ou);
1267
1268     $order_by ||= ['payment_ts'];
1269
1270     # all payments by user, between start_date and end_date
1271     my $payments = $e->json_query({
1272         select => {mp => ['id']}, 
1273         from => {
1274             mp => {
1275                 mbt => {
1276                     fkey => 'xact', field => 'id'}
1277             }
1278         }, 
1279         where => {
1280             '+mbt' => {usr => $user_id}, 
1281             '+mp' => {payment_ts => {between => [$start_date, $end_date]}}
1282         },
1283         order_by => {mp => $order_by}
1284     });
1285
1286     for my $payment_id (@$payments) {
1287         my $payment = $e->retrieve_money_payment([
1288             $payment_id->{id}, 
1289             {   
1290                 flesh => 2,
1291                 flesh_fields => {
1292                     mp => [
1293                         'xact',
1294                         'cash_payment',
1295                         'credit_card_payment',
1296                         'credit_payment',
1297                         'check_payment',
1298                         'work_payment',
1299                         'forgive_payment',
1300                         'goods_payment'
1301                     ],
1302                     mbt => [
1303                         'circulation', 
1304                         'grocery'
1305                     ]
1306                 }
1307             }
1308         ]);
1309         $conn->respond($payment);
1310     }
1311
1312     return undef;
1313 }
1314
1315
1316 __PACKAGE__->register_method(
1317         method  => "retrieve_circ_chain",
1318         api_name        => "open-ils.circ.renewal_chain.retrieve_by_circ",
1319     stream => 1,
1320         signature => {
1321         desc => q/Given a circulation, this returns all circulation objects
1322                 that are part of the same chain of renewals./,
1323         params => [
1324             {desc => 'Authentication token', type => 'string'},
1325             {desc => 'Circ ID', type => 'number'},
1326         ],
1327         return => {desc => q/List of circ objects, orderd by oldest circ first/}
1328     }
1329 );
1330
1331 sub retrieve_circ_chain {
1332     my($self, $conn, $auth, $circ_id) = @_;
1333
1334     my $e = new_editor(authtoken => $auth);
1335     return $e->event unless $e->checkauth;
1336
1337     # grab the base circ and all parent (previous) circs by fleshing
1338     my $base_circ = $e->retrieve_action_circulation([
1339         $circ_id,
1340         {
1341             flesh => -1,
1342             flesh_fields => {circ => ['parent_circ']}
1343         }
1344     ]) or return $e->event;
1345
1346     return $e->event unless $e->allowed('VIEW_CIRCULATIONS', $base_circ->circ_lib);
1347
1348     # send each circ to the caller, starting with the oldest circulation
1349     my @chain;
1350     my $circ = $base_circ;
1351     while($circ) {
1352         push(@chain, $circ);
1353
1354         # unflesh for consistency
1355         my $parent = $circ->parent_circ;
1356         $circ->parent_circ($parent->id) if $parent; 
1357
1358         $circ = $parent;
1359     }
1360     $conn->respond($_) for reverse(@chain);
1361
1362     # base circ may not be the end of the chain.  see if there are any subsequent circs
1363     $circ = $base_circ;
1364     $conn->respond($circ) while ($circ = $e->search_action_circulation({parent_circ => $circ->id})->[0]);
1365
1366     return undef;
1367 }
1368
1369
1370
1371 # {"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}}
1372
1373
1374 1;