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