]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ.pm
ranged (scoped by org/depth) billing_type retrieval method
[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
15 use DateTime;
16 use DateTime::Format::ISO8601;
17
18 use OpenILS::Application::AppUtils;
19
20 use OpenSRF::Utils qw/:datetime/;
21 use OpenILS::Utils::ModsParser;
22 use OpenILS::Event;
23 use OpenSRF::EX qw(:try);
24 use OpenSRF::Utils::Logger qw(:logger);
25 use OpenILS::Utils::Fieldmapper;
26 use OpenILS::Utils::Editor;
27 use OpenILS::Utils::CStoreEditor q/:funcs/;
28 use OpenILS::Const qw/:const/;
29 use OpenSRF::Utils::SettingsClient;
30
31 my $apputils = "OpenILS::Application::AppUtils";
32 my $U = $apputils;
33
34
35 # ------------------------------------------------------------------------
36 # Top level Circ package;
37 # ------------------------------------------------------------------------
38
39 sub initialize {
40         my $self = shift;
41         OpenILS::Application::Circ::Circulate->initialize();
42 }
43
44
45 __PACKAGE__->register_method(
46         method => 'retrieve_circ',
47         api_name        => 'open-ils.circ.retrieve',
48         signature => q/
49                 Retrieve a circ object by id
50                 @param authtoken Login session key
51                 @pararm circid The id of the circ object
52         /
53 );
54 sub retrieve_circ {
55         my( $s, $c, $a, $i ) = @_;
56         my $e = new_editor(authtoken => $a);
57         return $e->event unless $e->checkauth;
58         my $circ = $e->retrieve_action_circulation($i) or return $e->event;
59         if( $e->requestor->id ne $circ->usr ) {
60                 return $e->event unless $e->allowed('VIEW_CIRCULATIONS');
61         }
62         return $circ;
63 }
64
65
66 __PACKAGE__->register_method(
67         method => 'fetch_circ_mods',
68         api_name => 'open-ils.circ.circ_modifier.retrieve.all');
69 sub fetch_circ_mods {
70     my($self, $conn, $args) = @_;
71     my $mods = new_editor()->retrieve_all_config_circ_modifier;
72     return [ map {$_->code} @$mods ] unless $$args{full};
73     return $mods;
74 }
75
76 __PACKAGE__->register_method(
77         method => 'fetch_bill_types',
78         api_name => 'open-ils.circ.billing_type.retrieve.all');
79 sub fetch_bill_types {
80         my $conf = OpenSRF::Utils::SettingsClient->new;
81         return $conf->config_value(
82                 'apps', 'open-ils.circ', 'app_settings', 'billing_types', 'type' );
83 }
84
85
86 __PACKAGE__->register_method(
87     method => 'ranged_billing_types',
88     api_name => 'open-ils.circ.billing_type.ranged.retrieve.all');
89
90 sub ranged_billing_types {
91     my($self, $conn, $auth, $org_id, $depth) = @_;
92     my $e = new_editor(authtoken => $auth);
93     return $e->event unless $e->checkauth;
94     return $e->search_config_billing_type(
95         {owner => $U->get_org_full_path($org_id, $depth)});
96 }
97
98
99
100 # ------------------------------------------------------------------------
101 # Returns an array of {circ, record} hashes checked out by the user.
102 # ------------------------------------------------------------------------
103 __PACKAGE__->register_method(
104         method  => "checkouts_by_user",
105         api_name        => "open-ils.circ.actor.user.checked_out",
106         NOTES           => <<"  NOTES");
107         Returns a list of open circulations as a pile of objects.  each object
108         contains the relevant copy, circ, and record
109         NOTES
110
111 sub checkouts_by_user {
112         my( $self, $client, $user_session, $user_id ) = @_;
113
114         my( $requestor, $target, $copy, $record, $evt );
115
116         ( $requestor, $target, $evt ) = 
117                 $apputils->checkses_requestor( $user_session, $user_id, 'VIEW_CIRCULATIONS');
118         return $evt if $evt;
119
120         my $circs = $apputils->simplereq(
121                 'open-ils.cstore',
122                 "open-ils.cstore.direct.action.open_circulation.search.atomic", 
123                 { usr => $target->id, checkin_time => undef } );
124 #               { usr => $target->id } );
125
126         my @results;
127         for my $circ (@$circs) {
128
129                 ( $copy, $evt )  = $apputils->fetch_copy($circ->target_copy);
130                 return $evt if $evt;
131
132                 $logger->debug("Retrieving record for copy " . $circ->target_copy);
133
134                 ($record, $evt) = $apputils->fetch_record_by_copy( $circ->target_copy );
135                 return $evt if $evt;
136
137                 my $mods = $apputils->record_to_mvr($record);
138
139                 push( @results, { copy => $copy, circ => $circ, record => $mods } );
140         }
141
142         return \@results;
143
144 }
145
146
147
148 __PACKAGE__->register_method(
149         method  => "checkouts_by_user_slim",
150         api_name        => "open-ils.circ.actor.user.checked_out.slim",
151         NOTES           => <<"  NOTES");
152         Returns a list of open circulation objects
153         NOTES
154
155 # DEPRECAT ME?? XXX
156 sub checkouts_by_user_slim {
157         my( $self, $client, $user_session, $user_id ) = @_;
158
159         my( $requestor, $target, $copy, $record, $evt );
160
161         ( $requestor, $target, $evt ) = 
162                 $apputils->checkses_requestor( $user_session, $user_id, 'VIEW_CIRCULATIONS');
163         return $evt if $evt;
164
165         $logger->debug( 'User ' . $requestor->id . 
166                 " retrieving checked out items for user " . $target->id );
167
168         # XXX Make the call correct..
169         return $apputils->simplereq(
170                 'open-ils.cstore',
171                 "open-ils.cstore.direct.action.open_circulation.search.atomic", 
172                 { usr => $target->id, checkin_time => undef } );
173 #               { usr => $target->id } );
174 }
175
176
177 __PACKAGE__->register_method(
178         method  => "checkouts_by_user_opac",
179         api_name        => "open-ils.circ.actor.user.checked_out.opac",);
180
181 # XXX Deprecate Me
182 sub checkouts_by_user_opac {
183         my( $self, $client, $auth, $user_id ) = @_;
184
185         my $e = OpenILS::Utils::Editor->new( authtoken => $auth );
186         return $e->event unless $e->checkauth;
187         $user_id ||= $e->requestor->id;
188         return $e->event unless 
189                 my $patron = $e->retrieve_actor_user($user_id);
190
191         my $data;
192         my $search = {usr => $user_id, stop_fines => undef};
193
194         if( $user_id ne $e->requestor->id ) {
195                 $data = $e->search_action_circulation(
196                         $search, {checkperm=>1, permorg=>$patron->home_ou})
197                         or return $e->event;
198
199         } else {
200                 $data = $e->search_action_circulation($search);
201         }
202
203         return $data;
204 }
205
206
207 __PACKAGE__->register_method(
208         method  => "title_from_transaction",
209         api_name        => "open-ils.circ.circ_transaction.find_title",
210         NOTES           => <<"  NOTES");
211         Returns a mods object for the title that is linked to from the 
212         copy from the hold that created the given transaction
213         NOTES
214
215 sub title_from_transaction {
216         my( $self, $client, $login_session, $transactionid ) = @_;
217
218         my( $user, $circ, $title, $evt );
219
220         ( $user, $evt ) = $apputils->checkses( $login_session );
221         return $evt if $evt;
222
223         ( $circ, $evt ) = $apputils->fetch_circulation($transactionid);
224         return $evt if $evt;
225         
226         ($title, $evt) = $apputils->fetch_record_by_copy($circ->target_copy);
227         return $evt if $evt;
228
229         return $apputils->record_to_mvr($title);
230 }
231
232
233
234 __PACKAGE__->register_method(
235         method  => "new_set_circ_lost",
236         api_name        => "open-ils.circ.circulation.set_lost",
237         signature       => q/
238         Sets the copy and related open circulation to lost
239                 @param auth
240                 @param args : barcode
241         /
242 );
243
244
245 # ---------------------------------------------------------------------
246 # Sets a circulation to lost.  updates copy status to lost
247 # applies copy and/or prcoessing fees depending on org settings
248 # ---------------------------------------------------------------------
249 sub new_set_circ_lost {
250     my( $self, $conn, $auth, $args ) = @_;
251
252     my $e = new_editor(authtoken=>$auth, xact=>1);
253     return $e->die_event unless $e->checkauth;
254
255     my $barcode = $$args{barcode};
256     $logger->info("marking item lost $barcode");
257
258     # ---------------------------------------------------------------------
259     # gather the pieces
260     my $copy = $e->search_asset_copy([
261         {barcode=>$barcode, deleted=>'f'},
262         {flesh => 1, flesh_fields => {'acp' => ['call_number']}}])->[0] 
263             or return $e->die_event;
264
265     my $owning_lib = 
266         ($copy->call_number->id == OILS_PRECAT_CALL_NUMBER) ? 
267             $copy->circ_lib : $copy->call_number->owning_lib;
268
269     my $circ = $e->search_action_circulation(
270         {checkin_time => undef, target_copy => $copy->id} )->[0]
271             or return $e->die_event;
272
273     $e->allowed('SET_CIRC_LOST', $circ->circ_lib) or return $e->die_event;
274
275     return OpenILS::Event->new('COPY_MARKED_LOST')
276             if $copy->status == OILS_COPY_STATUS_LOST;
277
278     # ---------------------------------------------------------------------
279     # fetch the related org settings
280     my $proc_fee = $U->ou_ancestor_setting_value(
281         $owning_lib, OILS_SETTING_LOST_PROCESSING_FEE, $e) || 0;
282     my $void_overdue = $U->ou_ancestor_setting_value(
283         $owning_lib, OILS_SETTING_VOID_OVERDUE_ON_LOST, $e) || 0;
284
285     # ---------------------------------------------------------------------
286     # move the copy into LOST status
287     $copy->status(OILS_COPY_STATUS_LOST);
288     $copy->editor($e->requestor->id);
289     $copy->edit_date('now');
290     $e->update_asset_copy($copy) or return $e->die_event;
291
292     my $price = $U->get_copy_price($e, $copy, $copy->call_number);
293
294     if( $price > 0 ) {
295         my $evt = create_bill($e, $price, 'Lost Materials', $circ->id);
296         return $evt if $evt;
297     }
298
299     # ---------------------------------------------------------------------
300     # if there is a processing fee, charge that too
301     if( $proc_fee > 0 ) {
302         my $evt = create_bill($e, $proc_fee, 'Lost Materials Processing Fee', $circ->id);
303         return $evt if $evt;
304     }
305
306     # ---------------------------------------------------------------------
307     # mark the circ as lost and stop the fines
308     $circ->stop_fines(OILS_STOP_FINES_LOST);
309     $circ->stop_fines_time('now') unless $circ->stop_fines_time;
310     $e->update_action_circulation($circ) or return $e->die_event;
311
312     # ---------------------------------------------------------------------
313     # void all overdue fines on this circ if configured
314     if( $void_overdue ) {
315         my $evt = void_overdues($e, $circ);
316         return $evt if $evt;
317     }
318
319     my $evt = reopen_xact($e, $circ->id);
320     return $evt if $evt;
321
322     $e->commit;
323     return 1;
324 }
325
326 sub reopen_xact {
327     my($e, $xactid) = @_;
328
329     # -----------------------------------------------------------------
330     # make sure the transaction is not closed
331     my $xact = $e->retrieve_money_billable_transaction($xactid)
332         or return $e->die_event;
333
334     if( $xact->xact_finish ) {
335         my ($mbts) = $U->fetch_mbts($xactid, $e);
336         if( $mbts->balance_owed != 0 ) {
337             $logger->info("* re-opening xact $xactid, orig xact_finish is ".$xact->xact_finish);
338             $xact->clear_xact_finish;
339             $e->update_money_billable_transaction($xact)
340                 or return $e->die_event;
341         } 
342     }
343
344     return undef;
345 }
346
347
348 sub create_bill {
349         my( $e, $amount, $type, $xactid ) = @_;
350
351         $logger->info("The system is charging $amount [$type] on xact $xactid");
352
353     # -----------------------------------------------------------------
354     # now create the billing
355         my $bill = Fieldmapper::money::billing->new;
356         $bill->xact($xactid);
357         $bill->amount($amount);
358         $bill->billing_type($type); 
359         $bill->note('SYSTEM GENERATED');
360     $e->create_money_billing($bill) or return $e->die_event;
361
362         return undef;
363 }
364
365
366
367 # -----------------------------------------------------------------
368 # Voids overdue fines on the given circ.  if a backdate is 
369 # provided, then we only void back to the backdate
370 # -----------------------------------------------------------------
371 sub void_overdues {
372     my( $e, $circ, $backdate ) = @_;
373
374     my $bill_search = { 
375         xact => $circ->id, 
376         billing_type => OILS_BILLING_TYPE_OVERDUE_MATERIALS 
377     };
378
379     if( $backdate ) {
380         # ------------------------------------------------------------------
381         # Fines for overdue materials are assessed up to, but not including,
382         # one fine interval after the fines are applicable.  Here, we add
383         # one fine interval to the backdate to ensure that we are not 
384         # voiding fines that were applicable before the backdate.
385         # ------------------------------------------------------------------
386
387         # if there is a raw time component (e.g. from postgres), 
388         # turn it into an interval that interval_to_seconds can parse
389         my $duration = $circ->fine_interval;
390         $duration =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
391         my $interval = OpenSRF::Utils->interval_to_seconds($duration);
392
393         my $date = DateTime::Format::ISO8601->parse_datetime($backdate);
394         $backdate = $U->epoch2ISO8601($date->epoch + $interval);
395         $logger->info("applying backdate $backdate in overdue voiding");
396         $$bill_search{billing_ts} = {'>=' => $backdate};
397     }
398
399     my $bills = $e->search_money_billing($bill_search);
400     
401     for my $bill (@$bills) {
402         next if $U->is_true($bill->voided);
403         $logger->info("voiding overdue bill ".$bill->id);
404         $bill->voided('t');
405         $bill->void_time('now');
406         $bill->voider($e->requestor->id);
407         my $n = $bill->note || "";
408         $bill->note("$n\nSystem: VOIDED FOR BACKDATE");
409         $e->update_money_billing($bill) or return $e->die_event;
410     }
411
412         return undef;
413 }
414
415
416
417
418 __PACKAGE__->register_method(
419         method  => "set_circ_claims_returned",
420         api_name        => "open-ils.circ.circulation.set_claims_returned",
421         signature       => q/
422         Sets the circ for the given item as claims returned
423         If a backdate is provided, overdue fines will be voided
424         back to the backdate
425                 @param auth
426                 @param args : barcode, backdate
427         /
428 );
429
430 sub set_circ_claims_returned {
431     my( $self, $conn, $auth, $args ) = @_;
432
433     my $e = new_editor(authtoken=>$auth, xact=>1);
434     return $e->die_event unless $e->checkauth;
435
436     my $barcode = $$args{barcode};
437     my $backdate = $$args{backdate};
438
439     $logger->info("marking circ for item $barcode as claims returned".
440         (($backdate) ? " with backdate $backdate" : ''));
441
442     my $copy = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'})->[0] 
443         or return $e->die_event;
444
445     my $circ = $e->search_action_circulation(
446         {checkin_time => undef, target_copy => $copy->id})->[0]
447             or return $e->die_event;
448
449     $e->allowed('SET_CIRC_CLAIMS_RETURNED', $circ->circ_lib) 
450         or return $e->die_event;
451
452     $circ->stop_fines(OILS_STOP_FINES_CLAIMSRETURNED);
453         $circ->stop_fines_time('now') unless $circ->stop_fines_time;
454
455     if( $backdate ) {
456         # make it look like the circ stopped at the cliams returned time
457         $circ->stop_fines_time(clense_ISO8601($backdate));
458         my $evt = void_overdues($e, $circ, $backdate);
459         return $evt if $evt;
460     }
461
462     $e->update_action_circulation($circ) or return $e->die_event;
463     $e->commit;
464     return 1;
465 }
466
467
468
469
470
471 __PACKAGE__->register_method (
472         method          => 'set_circ_due_date',
473         api_name                => 'open-ils.circ.circulation.due_date.update',
474         signature       => q/
475                 Updates the due_date on the given circ
476                 @param authtoken
477                 @param circid The id of the circ to update
478                 @param date The timestamp of the new due date
479         /
480 );
481
482 sub set_circ_due_date {
483         my( $self, $conn, $auth, $circ_id, $date ) = @_;
484
485     my $e = new_editor(xact=>1, authtoken=>$auth);
486     return $e->die_event unless $e->checkauth;
487     my $circ = $e->retrieve_action_circulation($circ_id)
488         or return $e->die_event;
489
490     return $e->die_event unless $e->allowed('CIRC_OVERRIDE_DUE_DATE', $circ->circ_lib);
491         $date = clense_ISO8601($date);
492         $circ->due_date($date);
493     $e->update_action_circulation($circ) or return $e->die_event;
494     $e->commit;
495
496     return $circ->id;
497 }
498
499
500 __PACKAGE__->register_method(
501         method          => "create_in_house_use",
502         api_name                => 'open-ils.circ.in_house_use.create',
503         signature       =>      q/
504                 Creates an in-house use action.
505                 @param $authtoken The login session key
506                 @param params A hash of params including
507                         'location' The org unit id where the in-house use occurs
508                         'copyid' The copy in question
509                         'count' The number of in-house uses to apply to this copy
510                 @return An array of id's representing the id's of the newly created
511                 in-house use objects or an event on an error
512         /);
513
514 __PACKAGE__->register_method(
515         method          => "create_in_house_use",
516         api_name                => 'open-ils.circ.non_cat_in_house_use.create',
517 );
518
519
520 sub create_in_house_use {
521         my( $self, $client, $auth, $params ) = @_;
522
523         my( $evt, $copy );
524         my $org                 = $params->{location};
525         my $copyid              = $params->{copyid};
526         my $count               = $params->{count} || 1;
527         my $nc_type             = $params->{non_cat_type};
528         my $use_time    = $params->{use_time} || 'now';
529
530         my $e = new_editor(xact=>1,authtoken=>$auth);
531         return $e->event unless $e->checkauth;
532         return $e->event unless $e->allowed('CREATE_IN_HOUSE_USE');
533
534         my $non_cat = 1 if $self->api_name =~ /non_cat/;
535
536         unless( $non_cat ) {
537                 if( $copyid ) {
538                         $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
539                 } else {
540                         $copy = $e->search_asset_copy({barcode=>$params->{barcode}, deleted => 'f'})->[0]
541                                 or return $e->event;
542                         $copyid = $copy->id;
543                 }
544         }
545
546         if( $use_time ne 'now' ) {
547                 $use_time = clense_ISO8601($use_time);
548                 $logger->debug("in_house_use setting use time to $use_time");
549         }
550
551         my @ids;
552         for(1..$count) {
553
554                 my $ihu;
555                 my $method;
556                 my $cmeth;
557
558                 if($non_cat) {
559                         $ihu = Fieldmapper::action::non_cat_in_house_use->new;
560                         $ihu->item_type($nc_type);
561                         $method = 'open-ils.storage.direct.action.non_cat_in_house_use.create';
562                         $cmeth = "create_action_non_cat_in_house_use";
563
564                 } else {
565                         $ihu = Fieldmapper::action::in_house_use->new;
566                         $ihu->item($copyid);
567                         $method = 'open-ils.storage.direct.action.in_house_use.create';
568                         $cmeth = "create_action_in_house_use";
569                 }
570
571                 $ihu->staff($e->requestor->id);
572                 $ihu->org_unit($org);
573                 $ihu->use_time($use_time);
574
575                 $ihu = $e->$cmeth($ihu) or return $e->event;
576                 push( @ids, $ihu->id );
577         }
578
579         $e->commit;
580         return \@ids;
581 }
582
583
584
585
586
587 __PACKAGE__->register_method(
588         method  => "view_circs",
589         api_name        => "open-ils.circ.copy_checkout_history.retrieve",
590         notes           => q/
591                 Retrieves the last X circs for a given copy
592                 @param authtoken The login session key
593                 @param copyid The copy to check
594                 @param count How far to go back in the item history
595                 @return An array of circ ids
596         /);
597
598 # ----------------------------------------------------------------------
599 # Returns $count most recent circs.  If count exceeds the configured 
600 # max, use the configured max instead
601 # ----------------------------------------------------------------------
602 sub view_circs {
603         my( $self, $client, $authtoken, $copyid, $count ) = @_; 
604
605     my $e = new_editor(authtoken => $authtoken);
606     return $e->event unless $e->checkauth;
607     
608     my $copy = $e->retrieve_asset_copy([
609         $copyid,
610         {   flesh => 1,
611             flesh_fields => {acp => ['call_number']}
612         }
613     ]) or return $e->event;
614
615     return $e->event unless $e->allowed(
616         'VIEW_COPY_CHECKOUT_HISTORY', 
617         ($copy->call_number == OILS_PRECAT_CALL_NUMBER) ? 
618             $copy->circ_lib : $copy->call_number->owning_lib);
619         
620     my $max_history = $U->ou_ancestor_setting_value(
621         $e->requestor->ws_ou, 'circ.item_checkout_history.max', $e);
622
623     if(defined $max_history) {
624         $count = $max_history unless defined $count and $count < $max_history;
625     } else {
626         $count = 4 unless defined $count;
627     }
628
629     return $e->search_action_circulation([
630         {target_copy => $copyid}, 
631         {limit => $count, order_by => { circ => "xact_start DESC" }} 
632     ]);
633 }
634
635
636 __PACKAGE__->register_method(
637         method  => "circ_count",
638         api_name        => "open-ils.circ.circulation.count",
639         notes           => q/
640                 Returns the number of times the item has circulated
641                 @param copyid The copy to check
642         /);
643
644 sub circ_count {
645         my( $self, $client, $copyid, $range ) = @_; 
646         my $e = OpenILS::Utils::Editor->new;
647         return $e->request('open-ils.storage.asset.copy.circ_count', $copyid, $range);
648 }
649
650
651
652 __PACKAGE__->register_method(
653         method          => 'fetch_notes',
654         api_name                => 'open-ils.circ.copy_note.retrieve.all',
655         signature       => q/
656                 Returns an array of copy note objects.  
657                 @param args A named hash of parameters including:
658                         authtoken       : Required if viewing non-public notes
659                         itemid          : The id of the item whose notes we want to retrieve
660                         pub                     : True if all the caller wants are public notes
661                 @return An array of note objects
662         /);
663
664 __PACKAGE__->register_method(
665         method          => 'fetch_notes',
666         api_name                => 'open-ils.circ.call_number_note.retrieve.all',
667         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
668
669 __PACKAGE__->register_method(
670         method          => 'fetch_notes',
671         api_name                => 'open-ils.circ.title_note.retrieve.all',
672         signature       => q/@see open-ils.circ.copy_note.retrieve.all/);
673
674
675 # NOTE: VIEW_COPY/VOLUME/TITLE_NOTES perms should always be global
676 sub fetch_notes {
677         my( $self, $connection, $args ) = @_;
678
679         my $id = $$args{itemid};
680         my $authtoken = $$args{authtoken};
681         my( $r, $evt);
682
683         if( $self->api_name =~ /copy/ ) {
684                 if( $$args{pub} ) {
685                         return $U->cstorereq(
686                                 'open-ils.cstore.direct.asset.copy_note.search.atomic',
687                                 { owning_copy => $id, pub => 't' } );
688                 } else {
689                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_COPY_NOTES');
690                         return $evt if $evt;
691                         return $U->cstorereq(
692                                 'open-ils.cstore.direct.asset.copy_note.search.atomic', {owning_copy => $id} );
693                 }
694
695         } elsif( $self->api_name =~ /call_number/ ) {
696                 if( $$args{pub} ) {
697                         return $U->cstorereq(
698                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic',
699                                 { call_number => $id, pub => 't' } );
700                 } else {
701                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_VOLUME_NOTES');
702                         return $evt if $evt;
703                         return $U->cstorereq(
704                                 'open-ils.cstore.direct.asset.call_number_note.search.atomic', { call_number => $id } );
705                 }
706
707         } elsif( $self->api_name =~ /title/ ) {
708                 if( $$args{pub} ) {
709                         return $U->cstorereq(
710                                 'open-ils.cstore.direct.bilbio.record_note.search.atomic',
711                                 { record => $id, pub => 't' } );
712                 } else {
713                         ( $r, $evt ) = $U->checksesperm($authtoken, 'VIEW_TITLE_NOTES');
714                         return $evt if $evt;
715                         return $U->cstorereq(
716                                 'open-ils.cstore.direct.biblio.record_note.search.atomic', { record => $id } );
717                 }
718         }
719
720         return undef;
721 }
722
723 __PACKAGE__->register_method(
724         method  => 'has_notes',
725         api_name        => 'open-ils.circ.copy.has_notes');
726 __PACKAGE__->register_method(
727         method  => 'has_notes',
728         api_name        => 'open-ils.circ.call_number.has_notes');
729 __PACKAGE__->register_method(
730         method  => 'has_notes',
731         api_name        => 'open-ils.circ.title.has_notes');
732
733
734 sub has_notes {
735         my( $self, $conn, $authtoken, $id ) = @_;
736         my $editor = OpenILS::Utils::Editor->new(authtoken => $authtoken);
737         return $editor->event unless $editor->checkauth;
738
739         my $n = $editor->search_asset_copy_note(
740                 {owning_copy=>$id}, {idlist=>1}) if $self->api_name =~ /copy/;
741
742         $n = $editor->search_asset_call_number_note(
743                 {call_number=>$id}, {idlist=>1}) if $self->api_name =~ /call_number/;
744
745         $n = $editor->search_biblio_record_note(
746                 {record=>$id}, {idlist=>1}) if $self->api_name =~ /title/;
747
748         return scalar @$n;
749 }
750
751
752
753 __PACKAGE__->register_method(
754         method          => 'create_copy_note',
755         api_name                => 'open-ils.circ.copy_note.create',
756         signature       => q/
757                 Creates a new copy note
758                 @param authtoken The login session key
759                 @param note     The note object to create
760                 @return The id of the new note object
761         /);
762
763 sub create_copy_note {
764         my( $self, $connection, $authtoken, $note ) = @_;
765
766         my $e = new_editor(xact=>1, authtoken=>$authtoken);
767         return $e->event unless $e->checkauth;
768         my $copy = $e->retrieve_asset_copy(
769                 [
770                         $note->owning_copy,
771                         {       flesh => 1,
772                                 flesh_fields => { 'acp' => ['call_number'] }
773                         }
774                 ]
775         );
776
777         return $e->event unless 
778                 $e->allowed('CREATE_COPY_NOTE', $copy->call_number->owning_lib);
779
780         $note->create_date('now');
781         $note->creator($e->requestor->id);
782         $note->pub( ($U->is_true($note->pub)) ? 't' : 'f' );
783         $note->clear_id;
784
785         $e->create_asset_copy_note($note) or return $e->event;
786         $e->commit;
787         return $note->id;
788 }
789
790
791 __PACKAGE__->register_method(
792         method          => 'delete_copy_note',
793         api_name                =>      'open-ils.circ.copy_note.delete',
794         signature       => q/
795                 Deletes an existing copy note
796                 @param authtoken The login session key
797                 @param noteid The id of the note to delete
798                 @return 1 on success - Event otherwise.
799                 /);
800 sub delete_copy_note {
801         my( $self, $conn, $authtoken, $noteid ) = @_;
802
803         my $e = new_editor(xact=>1, authtoken=>$authtoken);
804         return $e->die_event unless $e->checkauth;
805
806         my $note = $e->retrieve_asset_copy_note([
807                 $noteid,
808                 { flesh => 2,
809                         flesh_fields => {
810                                 'acpn' => [ 'owning_copy' ],
811                                 'acp' => [ 'call_number' ],
812                         }
813                 }
814         ]) or return $e->die_event;
815
816         if( $note->creator ne $e->requestor->id ) {
817                 return $e->die_event unless 
818                         $e->allowed('DELETE_COPY_NOTE', $note->owning_copy->call_number->owning_lib);
819         }
820
821         $e->delete_asset_copy_note($note) or return $e->die_event;
822         $e->commit;
823         return 1;
824 }
825
826
827 __PACKAGE__->register_method(
828         method => 'age_hold_rules',
829         api_name        =>  'open-ils.circ.config.rules.age_hold_protect.retrieve.all',
830 );
831
832 sub age_hold_rules {
833         my( $self, $conn ) = @_;
834         return new_editor()->retrieve_all_config_rules_age_hold_protect();
835 }
836
837
838
839 __PACKAGE__->register_method(
840         method => 'copy_details_barcode',
841     authoritative => 1,
842         api_name => 'open-ils.circ.copy_details.retrieve.barcode');
843 sub copy_details_barcode {
844         my( $self, $conn, $auth, $barcode ) = @_;
845     my $e = new_editor();
846     my $cid = $e->search_asset_copy({barcode=>$barcode, deleted=>'f'}, {idlist=>1})->[0];
847     return $e->event unless $cid;
848         return copy_details( $self, $conn, $auth, $cid );
849 }
850
851
852 __PACKAGE__->register_method(
853         method => 'copy_details',
854         api_name => 'open-ils.circ.copy_details.retrieve');
855
856 sub copy_details {
857         my( $self, $conn, $auth, $copy_id ) = @_;
858         my $e = new_editor(authtoken=>$auth);
859         return $e->event unless $e->checkauth;
860
861         my $flesh = { flesh => 1 };
862
863         my $copy = $e->retrieve_asset_copy(
864                 [
865                         $copy_id,
866                         {
867                                 flesh => 2,
868                                 flesh_fields => {
869                                         acp => ['call_number'],
870                                         acn => ['record']
871                                 }
872                         }
873                 ]) or return $e->event;
874
875
876         # De-flesh the copy for backwards compatibility
877         my $mvr;
878         my $vol = $copy->call_number;
879         if( ref $vol ) {
880                 $copy->call_number($vol->id);
881                 my $record = $vol->record;
882                 if( ref $record ) {
883                         $vol->record($record->id);
884                         $mvr = $U->record_to_mvr($record);
885                 }
886         }
887
888
889         my $hold = $e->search_action_hold_request(
890                 { 
891                         current_copy            => $copy_id, 
892                         capture_time            => { "!=" => undef },
893                         fulfillment_time        => undef,
894                         cancel_time                     => undef,
895                 }
896         )->[0];
897
898         OpenILS::Application::Circ::Holds::flesh_hold_transits([$hold]) if $hold;
899
900         my $transit = $e->search_action_transit_copy(
901                 { target_copy => $copy_id, dest_recv_time => undef } )->[0];
902
903         # find the latest circ, open or closed
904         my $circ = $e->search_action_circulation(
905                 [
906                         { target_copy => $copy_id },
907                         { order_by => { circ => 'xact_start desc' }, limit => 1 }
908                 ]
909         )->[0];
910
911
912         return {
913                 copy            => $copy,
914                 hold            => $hold,
915                 transit => $transit,
916                 circ            => $circ,
917                 volume  => $vol,
918                 mvr             => $mvr,
919         };
920 }
921
922
923
924
925 __PACKAGE__->register_method(
926         method => 'mark_item',
927         api_name => 'open-ils.circ.mark_item_damaged',
928 );
929 __PACKAGE__->register_method(
930         method => 'mark_item',
931         api_name => 'open-ils.circ.mark_item_missing',
932 );
933
934 sub mark_item {
935         my( $self, $conn, $auth, $copy_id ) = @_;
936         my $e = new_editor(authtoken=>$auth, xact =>1);
937         return $e->event unless $e->checkauth;
938
939         my $perm = 'MARK_ITEM_MISSING';
940         my $stat = OILS_COPY_STATUS_MISSING;
941
942         if( $self->api_name =~ /damaged/ ) {
943                 $perm = 'MARK_ITEM_DAMAGED';
944                 $stat = OILS_COPY_STATUS_DAMAGED;
945         }
946
947         my $copy = $e->retrieve_asset_copy($copy_id)
948                 or return $e->event;
949         $copy->status($stat);
950         $copy->edit_date('now');
951         $copy->editor($e->requestor->id);
952
953         $e->update_asset_copy($copy) or return $e->event;
954
955
956         my $holds = $e->search_action_hold_request(
957                 { 
958                         current_copy => $copy->id,
959                         fulfillment_time => undef,
960                         cancel_time => undef,
961                 }
962         );
963
964         $e->commit;
965
966         $logger->debug("reseting holds that target the marked copy");
967         OpenILS::Application::Circ::Holds->_reset_hold($e->requestor, $_) for @$holds;
968
969         return 1;
970 }
971
972
973
974
975
976
977 # ----------------------------------------------------------------------
978 __PACKAGE__->register_method(
979         method => 'magic_fetch',
980         api_name => 'open-ils.agent.fetch'
981 );
982
983 my @FETCH_ALLOWED = qw/ aou aout acp acn bre /;
984
985 sub magic_fetch {
986         my( $self, $conn, $auth, $args ) = @_;
987         my $e = new_editor( authtoken => $auth );
988         return $e->event unless $e->checkauth;
989
990         my $hint = $$args{hint};
991         my $id  = $$args{id};
992
993         # Is the call allowed to fetch this type of object?
994         return undef unless grep { $_ eq $hint } @FETCH_ALLOWED;
995
996         # Find the class the iplements the given hint
997         my ($class) = grep { 
998                 $Fieldmapper::fieldmap->{$_}{hint} eq $hint } Fieldmapper->classes;
999
1000         $class =~ s/Fieldmapper:://og;
1001         $class =~ s/::/_/og;
1002         my $method = "retrieve_$class";
1003
1004         my $obj = $e->$method($id) or return $e->event;
1005         return $obj;
1006 }
1007 # ----------------------------------------------------------------------
1008
1009
1010 __PACKAGE__->register_method(
1011         method  => "fleshed_circ_retrieve",
1012     authoritative => 1,
1013         api_name        => "open-ils.circ.fleshed.retrieve",);
1014
1015 sub fleshed_circ_retrieve {
1016         my( $self, $client, $id ) = @_;
1017         my $e = new_editor();
1018         my $circ = $e->retrieve_action_circulation(
1019                 [
1020                         $id,
1021                         { 
1022                                 flesh                           => 4,
1023                                 flesh_fields    => { 
1024                                         circ => [ qw/ target_copy / ],
1025                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect call_number / ],
1026                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
1027                                         acn => [ qw/ record / ],
1028                                 }
1029                         }
1030                 ]
1031         ) or return $e->event;
1032         
1033         my $copy = $circ->target_copy;
1034         my $vol = $copy->call_number;
1035         my $rec = $circ->target_copy->call_number->record;
1036
1037         $vol->record($rec->id);
1038         $copy->call_number($vol->id);
1039         $circ->target_copy($copy->id);
1040
1041         my $mvr;
1042
1043         if( $rec->id == OILS_PRECAT_RECORD ) {
1044                 $rec = undef;
1045                 $vol = undef;
1046         } else { 
1047                 $mvr = $U->record_to_mvr($rec);
1048                 $rec->marc(''); # drop the bulky marc data
1049         }
1050
1051         return {
1052                 circ => $circ,
1053                 copy => $copy,
1054                 volume => $vol,
1055                 record => $rec,
1056                 mvr => $mvr,
1057         };
1058 }
1059
1060 # {"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}}
1061
1062
1063 1;