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