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