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