Bug 18255: Koha::Biblio - Replace GetBiblioItemByBiblioNumber with Koha::Biblio-...
[koha.git] / C4 / ILSDI / Services.pm
1 package C4::ILSDI::Services;
2
3 # Copyright 2009 SARL Biblibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22
23 use C4::Members;
24 use C4::Items;
25 use C4::Circulation;
26 use C4::Accounts;
27 use C4::Biblio;
28 use C4::Reserves qw(AddReserve CanBookBeReserved CanItemBeReserved IsAvailableForItemLevelRequest);
29 use C4::Context;
30 use C4::AuthoritiesMarc;
31 use XML::Simple;
32 use HTML::Entities;
33 use CGI qw ( -utf8 );
34 use DateTime;
35 use C4::Auth;
36 use C4::Members::Attributes qw(GetBorrowerAttributes);
37 use Koha::DateUtils;
38
39 use Koha::Biblios;
40 use Koha::Checkouts;
41 use Koha::Libraries;
42 use Koha::Patrons;
43
44 =head1 NAME
45
46 C4::ILS-DI::Services - ILS-DI Services
47
48 =head1 DESCRIPTION
49
50 Each function in this module represents an ILS-DI service.
51 They all takes a CGI instance as argument and most of them return a
52 hashref that will be printed by XML::Simple in opac/ilsdi.pl
53
54 =head1 SYNOPSIS
55
56     use C4::ILSDI::Services;
57     use XML::Simple;
58     use CGI qw ( -utf8 );
59
60     my $cgi = new CGI;
61
62     $out = LookupPatron($cgi);
63
64     print CGI::header('text/xml');
65     print XMLout($out,
66         noattr => 1,
67         noescape => 1,
68         nosort => 1,
69                 xmldecl => '<?xml version="1.0" encoding="UTF-8" ?>',
70         RootName => 'LookupPatron',
71         SuppressEmpty => 1);
72
73 =cut
74
75 =head1 FUNCTIONS
76
77 =head2 GetAvailability
78
79 Given a set of biblionumbers or itemnumbers, returns a list with
80 availability of the items associated with the identifiers.
81
82 Parameters:
83
84 =head3 id (Required)
85
86 list of either biblionumbers or itemnumbers
87
88 =head3 id_type (Required)
89
90 defines the type of record identifier being used in the request,
91 possible values:
92
93   - bib
94   - item
95
96 =head3 return_type (Optional)
97
98 requests a particular level of detail in reporting availability,
99 possible values:
100
101   - bib
102   - item
103
104 =head3 return_fmt (Optional)
105
106 requests a particular format or set of formats in reporting
107 availability
108
109 =cut
110
111 sub GetAvailability {
112     my ($cgi) = @_;
113
114     my $out = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
115     $out .= "<dlf:collection\n";
116     $out .= "  xmlns:dlf=\"http://diglib.org/ilsdi/1.1\"\n";
117     $out .= "  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
118     $out .= "  xsi:schemaLocation=\"http://diglib.org/ilsdi/1.1\n";
119     $out .= "    http://diglib.org/architectures/ilsdi/schemas/1.1/dlfexpanded.xsd\">\n";
120
121     foreach my $id ( split( / /, $cgi->param('id') ) ) {
122         if ( $cgi->param('id_type') eq "item" ) {
123             my ( $biblionumber, $status, $msg, $location ) = _availability($id);
124
125             $out .= "  <dlf:record>\n";
126             $out .= "    <dlf:bibliographic id=\"" . ( $biblionumber || $id ) . "\" />\n";
127             $out .= "    <dlf:items>\n";
128             $out .= "      <dlf:item id=\"" . $id . "\">\n";
129             $out .= "        <dlf:simpleavailability>\n";
130             $out .= "          <dlf:identifier>" . $id . "</dlf:identifier>\n";
131             $out .= "          <dlf:availabilitystatus>" . $status . "</dlf:availabilitystatus>\n";
132             if ($msg)      { $out .= "          <dlf:availabilitymsg>" . $msg . "</dlf:availabilitymsg>\n"; }
133             if ($location) { $out .= "          <dlf:location>" . $location . "</dlf:location>\n"; }
134             $out .= "        </dlf:simpleavailability>\n";
135             $out .= "      </dlf:item>\n";
136             $out .= "    </dlf:items>\n";
137             $out .= "  </dlf:record>\n";
138         } else {
139             my $status;
140             my $msg;
141             my $items = GetItemnumbersForBiblio($id);
142             if ($items) {
143                 # Open XML
144                 $out .= "  <dlf:record>\n";
145                 $out .= "    <dlf:bibliographic id=\"" .$id. "\" />\n";
146                 $out .= "    <dlf:items>\n";
147                 # We loop over the items to clean them
148                 foreach my $itemnumber (@$items) {
149                     my ( $biblionumber, $status, $msg, $location ) = _availability($itemnumber);
150                     $out .= "      <dlf:item id=\"" . $itemnumber . "\">\n";
151                     $out .= "        <dlf:simpleavailability>\n";
152                     $out .= "          <dlf:identifier>" . $itemnumber . "</dlf:identifier>\n";
153                     $out .= "          <dlf:availabilitystatus>" . $status . "</dlf:availabilitystatus>\n";
154                     if ($msg)      { $out .= "          <dlf:availabilitymsg>" . $msg . "</dlf:availabilitymsg>\n"; }
155                     if ($location) { $out .= "          <dlf:location>" . $location . "</dlf:location>\n"; }
156                     $out .= "        </dlf:simpleavailability>\n";
157                     $out .= "      </dlf:item>\n";
158                 }
159                 # Close XML
160                 $out .= "    </dlf:items>\n";
161                 $out .= "  </dlf:record>\n";
162             } else {
163                 $status = "unknown";
164                 $msg    = "Error: could not retrieve availability for this ID";
165             }
166         }
167     }
168     $out .= "</dlf:collection>\n";
169
170     return $out;
171 }
172
173 =head2 GetRecords
174
175 Given a list of biblionumbers, returns a list of record objects that
176 contain bibliographic information, as well as associated holdings and item
177 information. The caller may request a specific metadata schema for the
178 record objects to be returned.
179
180 This function behaves similarly to HarvestBibliographicRecords and
181 HarvestExpandedRecords in Data Aggregation, but allows quick, real time
182 lookup by bibliographic identifier.
183
184 You can use OAI-PMH ListRecords instead of this service.
185
186 Parameters:
187
188   - id (Required)
189     list of system record identifiers
190   - id_type (Optional)
191     Defines the metadata schema in which the records are returned,
192     possible values:
193         - MARCXML
194
195 =cut
196
197 sub GetRecords {
198     my ($cgi) = @_;
199
200     # Check if the schema is supported. For now, GetRecords only supports MARCXML
201     if ( $cgi->param('schema') and $cgi->param('schema') ne "MARCXML" ) {
202         return { code => 'UnsupportedSchema' };
203     }
204
205     my @records;
206
207     # Loop over biblionumbers
208     foreach my $biblionumber ( split( / /, $cgi->param('id') ) ) {
209
210         # Get the biblioitem from the biblionumber
211         my $biblio = Koha::Biblios->find( $biblionumber );
212         my $biblioitem = $biblio->biblioitem;
213         if ( $biblioitem ) {
214             $biblioitem = $biblioitem->unblessed;
215         } else {
216             $biblioitem->{code} = "RecordNotFound";
217             # FIXME We should not need to process something else; next?
218         }
219
220         my $embed_items = 1;
221         my $record = GetMarcBiblio({
222             biblionumber => $biblionumber,
223             embed_items  => $embed_items });
224         if ($record) {
225             $biblioitem->{marcxml} = $record->as_xml_record();
226         }
227
228         # Get most of the needed data
229         my $biblioitemnumber = $biblioitem->{'biblioitemnumber'};
230         my $holds  = $biblio->current_holds->unblessed;
231         my $issues           = GetBiblioIssues($biblionumber);
232         my $items            = GetItemsByBiblioitemnumber($biblioitemnumber);
233
234         # We loop over the items to clean them
235         foreach my $item (@$items) {
236
237             # This hides additionnal XML subfields, we don't need these info
238             delete $item->{'more_subfields_xml'};
239
240             # Display branch names instead of branch codes
241             my $home_library    = Koha::Libraries->find( $item->{homebranch} );
242             my $holding_library = Koha::Libraries->find( $item->{holdingbranch} );
243             $item->{'homebranchname'}    = $home_library    ? $home_library->branchname    : '';
244             $item->{'holdingbranchname'} = $holding_library ? $holding_library->branchname : '';
245         }
246
247         # Hashref building...
248         $biblioitem->{'items'}->{'item'}       = $items;
249         $biblioitem->{'reserves'}->{'reserve'} = $holds;
250         $biblioitem->{'issues'}->{'issue'}     = $issues;
251
252         push @records, $biblioitem;
253     }
254
255     return { record => \@records };
256 }
257
258 =head2 GetAuthorityRecords
259
260 Given a list of authority record identifiers, returns a list of record
261 objects that contain the authority records. The function user may request
262 a specific metadata schema for the record objects.
263
264 Parameters:
265
266   - id (Required)
267     list of authority record identifiers
268   - schema (Optional)
269     specifies the metadata schema of records to be returned, possible values:
270       - MARCXML
271
272 =cut
273
274 sub GetAuthorityRecords {
275     my ($cgi) = @_;
276
277     # If the user asks for an unsupported schema, return an error code
278     if ( $cgi->param('schema') and $cgi->param('schema') ne "MARCXML" ) {
279         return { code => 'UnsupportedSchema' };
280     }
281
282     my @records;
283
284     # Let's loop over the authority IDs
285     foreach my $authid ( split( / /, $cgi->param('id') ) ) {
286
287         # Get the record as XML string, or error code
288         push @records, GetAuthorityXML($authid) || { code => 'RecordNotFound' };
289     }
290
291     return { record => \@records };
292 }
293
294 =head2 LookupPatron
295
296 Looks up a patron in the ILS by an identifier, and returns the borrowernumber.
297
298 Parameters:
299
300   - id (Required)
301     an identifier used to look up the patron in Koha
302   - id_type (Optional)
303     the type of the identifier, possible values:
304     - cardnumber
305     - userid
306         - email
307     - borrowernumber
308     - firstname
309         - surname
310
311 =cut
312
313 sub LookupPatron {
314     my ($cgi) = @_;
315
316     my $id      = $cgi->param('id');
317     if(!$id) {
318         return { message => 'PatronNotFound' };
319     }
320
321     my $patrons;
322     my $passed_id_type = $cgi->param('id_type');
323     if($passed_id_type) {
324         $patrons = Koha::Patrons->search( { $passed_id_type => $id } );
325     } else {
326         foreach my $id_type ('cardnumber', 'userid', 'email', 'borrowernumber',
327                      'surname', 'firstname') {
328             $patrons = Koha::Patrons->search( { $id_type => $id } );
329             last if($patrons->count);
330         }
331     }
332     unless ( $patrons->count ) {
333         return { message => 'PatronNotFound' };
334     }
335
336     return { id => $patrons->next->borrowernumber };
337 }
338
339 =head2 AuthenticatePatron
340
341 Authenticates a user's login credentials and returns the identifier for
342 the patron.
343
344 Parameters:
345
346   - username (Required)
347     user's login identifier (userid or cardnumber)
348   - password (Required)
349     user's password
350
351 =cut
352
353 sub AuthenticatePatron {
354     my ($cgi) = @_;
355     my $username = $cgi->param('username');
356     my $password = $cgi->param('password');
357     my ($status, $cardnumber, $userid) = C4::Auth::checkpw( C4::Context->dbh, $username, $password );
358     if ( $status ) {
359         # Get the borrower
360         my $patron = Koha::Patrons->find( { cardnumber => $cardnumber } );
361         return { id => $patron->borrowernumber };
362     }
363     else {
364         return { code => 'PatronNotFound' };
365     }
366 }
367
368 =head2 GetPatronInfo
369
370 Returns specified information about the patron, based on options in the
371 request. This function can optionally return patron's contact information,
372 fine information, hold request information, and loan information.
373
374 Parameters:
375
376   - patron_id (Required)
377     the borrowernumber
378   - show_contact (Optional, default 1)
379     whether or not to return patron's contact information in the response
380   - show_fines (Optional, default 0)
381     whether or not to return fine information in the response
382   - show_holds (Optional, default 0)
383     whether or not to return hold request information in the response
384   - show_loans (Optional, default 0)
385     whether or not to return loan information request information in the response
386
387 =cut
388
389 sub GetPatronInfo {
390     my ($cgi) = @_;
391
392     # Get Member details
393     my $borrowernumber = $cgi->param('patron_id');
394     my $patron = Koha::Patrons->find( $borrowernumber );
395     return { code => 'PatronNotFound' } unless $patron;
396
397     # Cleaning the borrower hashref
398     my $borrower = $patron->unblessed;
399     $borrower->{charges} = sprintf "%.02f", $patron->account->non_issues_charges; # FIXME Formatting should not be done here
400     my $library = Koha::Libraries->find( $borrower->{branchcode} );
401     $borrower->{'branchname'} = $library ? $library->branchname : '';
402     delete $borrower->{'userid'};
403     delete $borrower->{'password'};
404
405     # Contact fields management
406     if ( defined $cgi->param('show_contact') && $cgi->param('show_contact') eq "0" ) {
407
408         # Define contact fields
409         my @contactfields = (
410             'email',              'emailpro',           'fax',                 'mobile',          'phone',             'phonepro',
411             'streetnumber',       'zipcode',            'city',                'streettype',      'B_address',         'B_city',
412             'B_email',            'B_phone',            'B_zipcode',           'address',         'address2',          'altcontactaddress1',
413             'altcontactaddress2', 'altcontactaddress3', 'altcontactfirstname', 'altcontactphone', 'altcontactsurname', 'altcontactzipcode'
414         );
415
416         # and delete them
417         foreach my $field (@contactfields) {
418             delete $borrower->{$field};
419         }
420     }
421
422     # Fines management
423     if ( $cgi->param('show_fines') && $cgi->param('show_fines') eq "1" ) {
424         my @charges;
425         for ( my $i = 1 ; my @charge = getcharges( $borrowernumber, undef, $i ) ; $i++ ) {
426             push( @charges, @charge );
427         }
428         $borrower->{'fines'}->{'fine'} = \@charges;
429     }
430
431     # Reserves management
432     if ( $cgi->param('show_holds') && $cgi->param('show_holds') eq "1" ) {
433
434         # Get borrower's reserves
435         my $holds = $patron->holds;
436         while ( my $hold = $holds->next ) {
437
438             my ( $item, $biblio, $biblioitem ) = ( {}, {}, {} );
439             # Get additional informations
440             if ( $hold->itemnumber ) {    # item level holds
441                 $item       = Koha::Items->find( $hold->itemnumber );
442                 $biblio     = $item->biblio;
443                 $biblioitem = $biblio->biblioitem;
444
445                 # Remove unwanted fields
446                 $item = $item->unblessed;
447                 delete $item->{more_subfields_xml};
448                 $biblio     = $biblio->unblessed;
449                 $biblioitem = $biblioitem->unblessed;
450             }
451
452             # Add additional fields
453             my $unblessed_hold = $hold->unblessed;
454             $unblessed_hold->{item}       = { %$item, %$biblio, %$biblioitem };
455             my $library = Koha::Libraries->find( $hold->branchcode );
456             my $branchname = $library ? $library->branchname : '';
457             $unblessed_hold->{branchname} = $branchname;
458             $biblio = Koha::Biblios->find( $hold->biblionumber ); # Should be $hold->get_biblio
459             $unblessed_hold->{title} = $biblio ? $biblio->title : ''; # Just in case, but should not be needed
460
461             push @{ $borrower->{holds}{hold} }, $unblessed_hold;
462
463         }
464     }
465
466     # Issues management
467     if ( $cgi->param('show_loans') && $cgi->param('show_loans') eq "1" ) {
468         my $issues = GetPendingIssues($borrowernumber);
469         foreach my $issue ( @$issues ){
470             $issue->{'issuedate'} = $issue->{'issuedate'}->strftime('%Y-%m-%d %H:%M');
471             $issue->{'date_due'} = $issue->{'date_due'}->strftime('%Y-%m-%d %H:%M');
472         }
473         $borrower->{'loans'}->{'loan'} = $issues;
474     }
475
476     if ( $cgi->param('show_attributes') eq "1" ) {
477         my $attrs = GetBorrowerAttributes( $borrowernumber, 0, 1 );
478         $borrower->{'attributes'} = $attrs;
479     }
480
481     return $borrower;
482 }
483
484 =head2 GetPatronStatus
485
486 Returns a patron's status information.
487
488 Parameters:
489
490   - patron_id (Required)
491     the borrower ID
492
493 =cut
494
495 sub GetPatronStatus {
496     my ($cgi) = @_;
497
498     # Get Member details
499     my $borrowernumber = $cgi->param('patron_id');
500     my $patron = Koha::Patrons->find( $borrowernumber );
501     return { code => 'PatronNotFound' } unless $patron;
502
503     # Return the results
504     return {
505         type   => $patron->categorycode,
506         status => 0, # TODO
507         expiry => $patron->dateexpiry,
508     };
509 }
510
511 =head2 GetServices
512
513 Returns information about the services available on a particular item for
514 a particular patron.
515
516 Parameters:
517
518   - patron_id (Required)
519     a borrowernumber
520   - item_id (Required)
521     an itemnumber
522
523 =cut
524
525 sub GetServices {
526     my ($cgi) = @_;
527
528     # Get the member, or return an error code if not found
529     my $borrowernumber = $cgi->param('patron_id');
530     my $patron = Koha::Patrons->find( $borrowernumber );
531     return { code => 'PatronNotFound' } unless $patron;
532
533     my $borrower = $patron->unblessed;
534     # Get the item, or return an error code if not found
535     my $itemnumber = $cgi->param('item_id');
536     my $item = GetItem( $itemnumber );
537     return { code => 'RecordNotFound' } unless $$item{itemnumber};
538
539     my @availablefor;
540
541     # Reserve level management
542     my $biblionumber = $item->{'biblionumber'};
543     my $canbookbereserved = CanBookBeReserved( $borrower, $biblionumber );
544     if ($canbookbereserved eq 'OK') {
545         push @availablefor, 'title level hold';
546         my $canitembereserved = IsAvailableForItemLevelRequest($item, $borrower);
547         if ($canitembereserved) {
548             push @availablefor, 'item level hold';
549         }
550     }
551
552     # Reserve cancellation management
553     my $holds = $patron->holds;
554     my @reserveditems;
555     while ( my $hold = $holds->next ) { # FIXME This could be improved
556         push @reserveditems, $hold->itemnumber;
557     }
558     if ( grep { $itemnumber eq $_ } @reserveditems ) {
559         push @availablefor, 'hold cancellation';
560     }
561
562     # Renewal management
563     my @renewal = CanBookBeRenewed( $borrowernumber, $itemnumber );
564     if ( $renewal[0] ) {
565         push @availablefor, 'loan renewal';
566     }
567
568     # Issuing management
569     my $barcode = $item->{'barcode'} || '';
570     $barcode = barcodedecode($barcode) if ( $barcode && C4::Context->preference('itemBarcodeInputFilter') );
571     if ($barcode) {
572         my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $barcode );
573
574         # TODO push @availablefor, 'loan';
575     }
576
577     my $out;
578     $out->{'AvailableFor'} = \@availablefor;
579
580     return $out;
581 }
582
583 =head2 RenewLoan
584
585 Extends the due date for a borrower's existing issue.
586
587 Parameters:
588
589   - patron_id (Required)
590     a borrowernumber
591   - item_id (Required)
592     an itemnumber
593   - desired_due_date (Required)
594     the date the patron would like the item returned by
595
596 =cut
597
598 sub RenewLoan {
599     my ($cgi) = @_;
600
601     # Get borrower infos or return an error code
602     my $borrowernumber = $cgi->param('patron_id');
603     my $patron = Koha::Patrons->find( $borrowernumber );
604     return { code => 'PatronNotFound' } unless $patron;
605
606     # Get the item, or return an error code
607     my $itemnumber = $cgi->param('item_id');
608     my $item = GetItem( $itemnumber );
609     return { code => 'RecordNotFound' } unless $$item{itemnumber};
610
611     # Add renewal if possible
612     my @renewal = CanBookBeRenewed( $borrowernumber, $itemnumber );
613     if ( $renewal[0] ) { AddRenewal( $borrowernumber, $itemnumber ); }
614
615     my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } ) or return; # FIXME should be handled
616
617     # Hashref building
618     my $out;
619     $out->{'renewals'} = $issue->renewals;
620     $out->{date_due}   = dt_from_string($issue->date_due)->strftime('%Y-%m-%d %H:%S');
621     $out->{'success'}  = $renewal[0];
622     $out->{'error'}    = $renewal[1];
623
624     return $out;
625 }
626
627 =head2 HoldTitle
628
629 Creates, for a borrower, a biblio-level hold reserve.
630
631 Parameters:
632
633   - patron_id (Required)
634     a borrowernumber
635   - bib_id (Required)
636     a biblionumber
637   - request_location (Required)
638     IP address where the end user request is being placed
639   - pickup_location (Optional)
640     a branch code indicating the location to which to deliver the item for pickup
641   - needed_before_date (Optional)
642     date after which hold request is no longer needed
643   - pickup_expiry_date (Optional)
644     date after which item returned to shelf if item is not picked up
645
646 =cut
647
648 sub HoldTitle {
649     my ($cgi) = @_;
650
651     # Get the borrower or return an error code
652     my $borrowernumber = $cgi->param('patron_id');
653     my $patron = Koha::Patrons->find( $borrowernumber );
654     return { code => 'PatronNotFound' } unless $patron;
655
656     # Get the biblio record, or return an error code
657     my $biblionumber = $cgi->param('bib_id');
658     my $biblio = Koha::Biblios->find( $biblionumber );
659     return { code => 'RecordNotFound' } unless $biblio;
660
661     my $title = $biblio ? $biblio->title : '';
662
663     # Check if the biblio can be reserved
664     return { code => 'NotHoldable' } unless CanBookBeReserved( $borrowernumber, $biblionumber ) eq 'OK';
665
666     my $branch;
667
668     # Pickup branch management
669     if ( $cgi->param('pickup_location') ) {
670         $branch = $cgi->param('pickup_location');
671         return { code => 'LocationNotFound' } unless Koha::Libraries->find($branch);
672     } else { # if the request provide no branch, use the borrower's branch
673         $branch = $patron->branchcode;
674     }
675
676     # Add the reserve
677     #    $branch,    $borrowernumber, $biblionumber,
678     #    $constraint, $bibitems,  $priority, $resdate, $expdate, $notes,
679     #    $title,      $checkitem, $found
680     my $priority= C4::Reserves::CalculatePriority( $biblionumber );
681     AddReserve( $branch, $borrowernumber, $biblionumber, undef, $priority, undef, undef, undef, $title, undef, undef );
682
683     # Hashref building
684     my $out;
685     $out->{'title'}           = $title;
686     my $library = Koha::Libraries->find( $branch );
687     $out->{'pickup_location'} = $library ? $library->branchname : '';
688
689     # TODO $out->{'date_available'}  = '';
690
691     return $out;
692 }
693
694 =head2 HoldItem
695
696 Creates, for a borrower, an item-level hold request on a specific item of
697 a bibliographic record in Koha.
698
699 Parameters:
700
701   - patron_id (Required)
702     a borrowernumber
703   - bib_id (Required)
704     a biblionumber
705   - item_id (Required)
706     an itemnumber
707   - pickup_location (Optional)
708     a branch code indicating the location to which to deliver the item for pickup
709   - needed_before_date (Optional)
710     date after which hold request is no longer needed
711   - pickup_expiry_date (Optional)
712     date after which item returned to shelf if item is not picked up
713
714 =cut
715
716 sub HoldItem {
717     my ($cgi) = @_;
718
719     # Get the borrower or return an error code
720     my $borrowernumber = $cgi->param('patron_id');
721     my $patron = Koha::Patrons->find( $borrowernumber );
722     return { code => 'PatronNotFound' } unless $patron;
723
724     # Get the biblio or return an error code
725     my $biblionumber = $cgi->param('bib_id');
726     my $biblio = Koha::Biblios->find( $biblionumber );
727     return { code => 'RecordNotFound' } unless $biblio;
728
729     my $title = $biblio ? $biblio->title : '';
730
731     # Get the item or return an error code
732     my $itemnumber = $cgi->param('item_id');
733     my $item = GetItem( $itemnumber );
734     return { code => 'RecordNotFound' } unless $$item{itemnumber};
735
736     # If the biblio does not match the item, return an error code
737     return { code => 'RecordNotFound' } if $$item{biblionumber} ne $biblio->biblionumber;
738
739     # Check for item disponibility
740     my $canitembereserved = C4::Reserves::CanItemBeReserved( $borrowernumber, $itemnumber );
741     my $canbookbereserved = C4::Reserves::CanBookBeReserved( $borrowernumber, $biblionumber );
742     return { code => 'NotHoldable' } unless $canbookbereserved eq 'OK' and $canitembereserved eq 'OK';
743
744     # Pickup branch management
745     my $branch;
746     if ( $cgi->param('pickup_location') ) {
747         $branch = $cgi->param('pickup_location');
748         return { code => 'LocationNotFound' } unless Koha::Libraries->find($branch);
749     } else { # if the request provide no branch, use the borrower's branch
750         $branch = $patron->branchcode;
751     }
752
753     # Add the reserve
754     #    $branch,    $borrowernumber, $biblionumber,
755     #    $constraint, $bibitems,  $priority, $resdate, $expdate, $notes,
756     #    $title,      $checkitem, $found
757     my $priority= C4::Reserves::CalculatePriority( $biblionumber );
758     AddReserve( $branch, $borrowernumber, $biblionumber, undef, $priority, undef, undef, undef, $title, $itemnumber, undef );
759
760     # Hashref building
761     my $out;
762     my $library = Koha::Libraries->find( $branch );
763     $out->{'pickup_location'} = $library ? $library->branchname : '';
764
765     # TODO $out->{'date_available'} = '';
766
767     return $out;
768 }
769
770 =head2 CancelHold
771
772 Cancels an active reserve request for the borrower.
773
774 Parameters:
775
776   - patron_id (Required)
777         a borrowernumber
778   - item_id (Required)
779         a reserve_id
780
781 =cut
782
783 sub CancelHold {
784     my ($cgi) = @_;
785
786     # Get the borrower or return an error code
787     my $borrowernumber = $cgi->param('patron_id');
788     my $patron = Koha::Patrons->find( $borrowernumber );
789     return { code => 'PatronNotFound' } unless $patron;
790
791     # Get the reserve or return an error code
792     my $reserve_id = $cgi->param('item_id');
793     my $hold = Koha::Holds->find( $reserve_id );
794     return { code => 'RecordNotFound' } unless $hold;
795     return { code => 'RecordNotFound' } unless ($hold->borrowernumber == $borrowernumber);
796
797     $hold->cancel;
798
799     return { code => 'Canceled' };
800 }
801
802 =head2 _availability
803
804 Returns, for an itemnumber, an array containing availability information.
805
806  my ($biblionumber, $status, $msg, $location) = _availability($id);
807
808 =cut
809
810 sub _availability {
811     my ($itemnumber) = @_;
812     my $item = GetItem( $itemnumber, undef, undef );
813
814     if ( not $item->{'itemnumber'} ) {
815         return ( undef, 'unknown', 'Error: could not retrieve availability for this ID', undef );
816     }
817
818     my $biblionumber = $item->{'biblioitemnumber'};
819     my $library = Koha::Libraries->find( $item->{holdingbranch} );
820     my $location = $library ? $library->branchname : '';
821
822     if ( $item->{'notforloan'} ) {
823         return ( $biblionumber, 'not available', 'Not for loan', $location );
824     } elsif ( $item->{'onloan'} ) {
825         return ( $biblionumber, 'not available', 'Checked out', $location );
826     } elsif ( $item->{'itemlost'} ) {
827         return ( $biblionumber, 'not available', 'Item lost', $location );
828     } elsif ( $item->{'withdrawn'} ) {
829         return ( $biblionumber, 'not available', 'Item withdrawn', $location );
830     } elsif ( $item->{'damaged'} ) {
831         return ( $biblionumber, 'not available', 'Item damaged', $location );
832     } else {
833         return ( $biblionumber, 'available', undef, $location );
834     }
835 }
836
837 1;