bug 5825: (follow-up) consult item-level_itypes
[koha.git] / C4 / HoldsQueue.pm
1 package C4::HoldsQueue;
2
3 # Copyright 2011 Catalyst IT
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 # FIXME: expand perldoc, explain intended logic
21
22 use strict;
23 use warnings;
24
25 use C4::Context;
26 use C4::Search;
27 use C4::Items;
28 use C4::Branch;
29 use C4::Circulation;
30 use C4::Members;
31 use C4::Biblio;
32 use C4::Dates qw/format_date/;
33
34 use List::Util qw(shuffle);
35 use Data::Dumper;
36
37 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
38 BEGIN {
39     $VERSION = 3.03;
40     require Exporter;
41     @ISA = qw(Exporter);
42     @EXPORT_OK = qw(
43         &CreateQueue
44         &GetHoldsQueueItems
45
46         &TransportCostMatrix
47         &UpdateTransportCostMatrix
48      );
49 }
50
51
52 =head1 FUNCTIONS
53
54 =head2 TransportCostMatrix
55
56   TransportCostMatrix();
57
58 Returns Transport Cost Matrix as a hashref <to branch code> => <from branch code> => cost
59
60 =cut
61
62 sub TransportCostMatrix {
63     my $dbh   = C4::Context->dbh;
64     my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} });
65
66     my %transport_cost_matrix;
67     foreach (@$transport_costs) {
68         my $from = $_->{frombranch};
69         my $to = $_->{tobranch};
70         my $cost = $_->{cost};
71         my $disabled = $_->{disable_transfer};
72         $transport_cost_matrix{$to}{$from} = { cost => $cost, disable_transfer => $disabled };
73     }
74     return \%transport_cost_matrix;
75 }
76
77 =head2 UpdateTransportCostMatrix
78
79   UpdateTransportCostMatrix($records);
80
81 Updates full Transport Cost Matrix table. $records is an arrayref of records.
82 Records: { frombranch => <code>, tobranch => <code>, cost => <figure>, disable_transfer => <0,1> }
83
84 =cut
85
86 sub UpdateTransportCostMatrix {
87     my ($records) = @_;
88     my $dbh   = C4::Context->dbh;
89
90     my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
91
92     $dbh->do("TRUNCATE TABLE transport_cost");
93     foreach (@$records) {
94         my $cost = $_->{cost};
95         my $from = $_->{frombranch};
96         my $to = $_->{tobranch};
97         if ($_->{disable_transfer}) {
98             $cost ||= 0;
99         }
100         elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) {
101             warn  "Invalid $from -> $to cost $cost - must be a number >= 0, disablig";
102             $cost = 0;
103             $_->{disable_transfer} = 1;
104         }
105         $sth->execute( $from, $to, $cost, $_->{disable_transfer} ? 1 : 0 );
106     }
107 }
108
109 =head2 GetHoldsQueueItems
110
111   GetHoldsQueueItems($branch);
112
113 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
114
115 =cut
116
117 sub GetHoldsQueueItems {
118     my ($branchlimit) = @_;
119     my $dbh   = C4::Context->dbh;
120
121     my @bind_params = ();
122     my $query = q/SELECT tmp_holdsqueue.*, biblio.author, items.ccode, items.itype, biblioitems.itemtype, items.location, items.enumchron, items.cn_sort, biblioitems.publishercode,biblio.copyrightdate,biblioitems.publicationyear,biblioitems.pages,biblioitems.size,biblioitems.publicationyear,biblioitems.isbn,items.copynumber
123                   FROM tmp_holdsqueue
124                        JOIN biblio      USING (biblionumber)
125                   LEFT JOIN biblioitems USING (biblionumber)
126                   LEFT JOIN items       USING (  itemnumber)
127                 /;
128     if ($branchlimit) {
129         $query .=" WHERE tmp_holdsqueue.holdingbranch = ?";
130         push @bind_params, $branchlimit;
131     }
132     $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
133     my $sth = $dbh->prepare($query);
134     $sth->execute(@bind_params);
135     my $items = [];
136     while ( my $row = $sth->fetchrow_hashref ){
137         $row->{reservedate} = format_date($row->{reservedate});
138         my $record = GetMarcBiblio($row->{biblionumber});
139         if ($record){
140             $row->{subtitle} = GetRecordValue('subtitle',$record,'')->[0]->{subfield};
141             $row->{parts} = GetRecordValue('parts',$record,'')->[0]->{subfield};
142             $row->{numbers} = GetRecordValue('numbers',$record,'')->[0]->{subfield};
143         }
144
145         # return the bib-level or item-level itype per syspref
146         if (!C4::Context->preference('item-level_itypes')) {
147             $row->{itype} = $row->{itemtype};
148         }
149         delete $row->{itemtype};
150
151         push @$items, $row;
152     }
153     return $items;
154 }
155
156 =head2 CreateQueue
157
158   CreateQueue();
159
160 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
161
162 =cut
163
164 sub CreateQueue {
165     my $dbh   = C4::Context->dbh;
166
167     $dbh->do("DELETE FROM tmp_holdsqueue");  # clear the old table for new info
168     $dbh->do("DELETE FROM hold_fill_targets");
169
170     my $total_bibs            = 0;
171     my $total_requests        = 0;
172     my $total_available_items = 0;
173     my $num_items_mapped      = 0;
174
175     my $branches_to_use;
176     my $transport_cost_matrix;
177     my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
178     if ($use_transport_cost_matrix) {
179         $transport_cost_matrix = TransportCostMatrix();
180         unless (keys %$transport_cost_matrix) {
181             warn "UseTransportCostMatrix set to yes, but matrix not populated";
182             undef $transport_cost_matrix;
183         }
184     }
185     unless ($transport_cost_matrix) {
186         $branches_to_use = load_branches_to_pull_from();
187     }
188
189     my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
190
191     foreach my $biblionumber (@$bibs_with_pending_requests) {
192         $total_bibs++;
193         my $hold_requests   = GetPendingHoldRequestsForBib($biblionumber);
194         my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_to_use);
195         $total_requests        += scalar(@$hold_requests);
196         $total_available_items += scalar(@$available_items);
197
198         my $item_map = MapItemsToHoldRequests($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix);
199         $item_map  or next;
200         my $item_map_size = scalar(keys %$item_map)
201           or next;
202
203         $num_items_mapped += $item_map_size;
204         CreatePicklistFromItemMap($item_map);
205         AddToHoldTargetMap($item_map);
206         if (($item_map_size < scalar(@$hold_requests  )) and
207             ($item_map_size < scalar(@$available_items))) {
208             # DOUBLE CHECK, but this is probably OK - unfilled item-level requests
209             # FIXME
210             #warn "unfilled requests for $biblionumber";
211             #warn Dumper($hold_requests), Dumper($available_items), Dumper($item_map);
212         }
213     }
214 }
215
216 =head2 GetBibsWithPendingHoldRequests
217
218   my $biblionumber_aref = GetBibsWithPendingHoldRequests();
219
220 Return an arrayref of the biblionumbers of all bibs
221 that have one or more unfilled hold requests.
222
223 =cut
224
225 sub GetBibsWithPendingHoldRequests {
226     my $dbh = C4::Context->dbh;
227
228     my $bib_query = "SELECT DISTINCT biblionumber
229                      FROM reserves
230                      WHERE found IS NULL
231                      AND priority > 0
232                      AND reservedate <= CURRENT_DATE()
233                      AND suspend = 0
234                      ";
235     my $sth = $dbh->prepare($bib_query);
236
237     $sth->execute();
238     my $biblionumbers = $sth->fetchall_arrayref();
239
240     return [ map { $_->[0] } @$biblionumbers ];
241 }
242
243 =head2 GetPendingHoldRequestsForBib
244
245   my $requests = GetPendingHoldRequestsForBib($biblionumber);
246
247 Returns an arrayref of hashrefs to pending, unfilled hold requests
248 on the bib identified by $biblionumber.  The following keys
249 are present in each hashref:
250
251     biblionumber
252     borrowernumber
253     itemnumber
254     priority
255     branchcode
256     reservedate
257     reservenotes
258     borrowerbranch
259
260 The arrayref is sorted in order of increasing priority.
261
262 =cut
263
264 sub GetPendingHoldRequestsForBib {
265     my $biblionumber = shift;
266
267     my $dbh = C4::Context->dbh;
268
269     my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserves.branchcode,
270                                 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch
271                          FROM reserves
272                          JOIN borrowers USING (borrowernumber)
273                          WHERE biblionumber = ?
274                          AND found IS NULL
275                          AND priority > 0
276                          AND reservedate <= CURRENT_DATE()
277                          AND suspend = 0
278                          ORDER BY priority";
279     my $sth = $dbh->prepare($request_query);
280     $sth->execute($biblionumber);
281
282     my $requests = $sth->fetchall_arrayref({});
283     return $requests;
284
285 }
286
287 =head2 GetItemsAvailableToFillHoldRequestsForBib
288
289   my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
290
291 Returns an arrayref of items available to fill hold requests
292 for the bib identified by C<$biblionumber>.  An item is available
293 to fill a hold request if and only if:
294
295     * it is not on loan
296     * it is not withdrawn
297     * it is not marked notforloan
298     * it is not currently in transit
299     * it is not lost
300     * it is not sitting on the hold shelf
301
302 =cut
303
304 sub GetItemsAvailableToFillHoldRequestsForBib {
305     my ($biblionumber, $branches_to_use) = @_;
306
307     my $dbh = C4::Context->dbh;
308     my $items_query = "SELECT itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
309                        FROM items ";
310
311     if (C4::Context->preference('item-level_itypes')) {
312         $items_query .=   "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
313     } else {
314         $items_query .=   "JOIN biblioitems USING (biblioitemnumber)
315                            LEFT JOIN itemtypes USING (itemtype) ";
316     }
317     $items_query .=   "WHERE items.notforloan = 0
318                        AND holdingbranch IS NOT NULL
319                        AND itemlost = 0
320                        AND wthdrawn = 0";
321     $items_query .= "  AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
322     $items_query .= "  AND items.onloan IS NULL
323                        AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
324                        AND itemnumber NOT IN (
325                            SELECT itemnumber
326                            FROM reserves
327                            WHERE biblionumber = ?
328                            AND itemnumber IS NOT NULL
329                            AND (found IS NOT NULL OR priority = 0)
330                         )
331                        AND items.biblionumber = ?";
332     $items_query .=  " AND damaged = 0 "
333       unless C4::Context->preference('AllowHoldsOnDamagedItems');
334
335     my @params = ($biblionumber, $biblionumber);
336     if ($branches_to_use && @$branches_to_use) {
337         $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
338         push @params, @$branches_to_use;
339     }
340     my $sth = $dbh->prepare($items_query);
341     $sth->execute(@params);
342
343     my $itm = $sth->fetchall_arrayref({});
344     my @items = grep { ! scalar GetTransfers($_->{itemnumber}) } @$itm;
345     return [ grep {
346         my $rule = GetBranchItemRule($_->{homebranch}, $_->{itype});
347         $_->{holdallowed} = $rule->{holdallowed} != 0
348     } @items ];
349 }
350
351 =head2 MapItemsToHoldRequests
352
353   MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
354
355 =cut
356
357 sub MapItemsToHoldRequests {
358     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
359
360     # handle trival cases
361     return unless scalar(@$hold_requests) > 0;
362     return unless scalar(@$available_items) > 0;
363
364     my $automatic_return = C4::Context->preference("AutomaticItemReturn");
365
366     # identify item-level requests
367     my %specific_items_requested = map { $_->{itemnumber} => 1 }
368                                    grep { defined($_->{itemnumber}) }
369                                    @$hold_requests;
370
371     # group available items by itemnumber
372     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
373
374     # items already allocated
375     my %allocated_items = ();
376
377     # map of items to hold requests
378     my %item_map = ();
379
380     # figure out which item-level requests can be filled
381     my $num_items_remaining = scalar(@$available_items);
382     foreach my $request (@$hold_requests) {
383         last if $num_items_remaining == 0;
384
385         # is this an item-level request?
386         if (defined($request->{itemnumber})) {
387             # fill it if possible; if not skip it
388             if (exists $items_by_itemnumber{$request->{itemnumber}} and
389                 not exists $allocated_items{$request->{itemnumber}}) {
390                 $item_map{$request->{itemnumber}} = {
391                     borrowernumber => $request->{borrowernumber},
392                     biblionumber => $request->{biblionumber},
393                     holdingbranch =>  $items_by_itemnumber{$request->{itemnumber}}->{holdingbranch},
394                     pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
395                     item_level => 1,
396                     reservedate => $request->{reservedate},
397                     reservenotes => $request->{reservenotes},
398                 };
399                 $allocated_items{$request->{itemnumber}}++;
400                 $num_items_remaining--;
401             }
402         } else {
403             # it's title-level request that will take up one item
404             $num_items_remaining--;
405         }
406     }
407
408     # group available items by branch
409     my %items_by_branch = ();
410     foreach my $item (@$available_items) {
411         next unless $item->{holdallowed};
412
413         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
414           unless exists $allocated_items{ $item->{itemnumber} };
415     }
416     return \%item_map unless keys %items_by_branch;
417
418     # now handle the title-level requests
419     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
420     my $pull_branches;
421     foreach my $request (@$hold_requests) {
422         last if $num_items_remaining == 0;
423         next if defined($request->{itemnumber}); # already handled these
424
425         # look for local match first
426         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
427         my ($itemnumber, $holdingbranch);
428
429         my $holding_branch_items = $automatic_return ? undef : $items_by_branch{$pickup_branch};
430         if ( $holding_branch_items ) {
431             foreach my $item (@$holding_branch_items) {
432                 if ( $request->{borrowerbranch} eq $item->{homebranch} ) {
433                     $itemnumber = $item->{itemnumber};
434                     last;
435                 }
436             }
437             $holdingbranch = $pickup_branch;
438             $itemnumber ||= $holding_branch_items->[0]->{itemnumber};
439         }
440         elsif ($transport_cost_matrix) {
441             $pull_branches = [keys %items_by_branch];
442             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
443             if ( $holdingbranch ) {
444
445                 my $holding_branch_items = $items_by_branch{$holdingbranch};
446                 foreach my $item (@$holding_branch_items) {
447                     next if $request->{borrowerbranch} ne $item->{homebranch};
448
449                     $itemnumber = $item->{itemnumber};
450                     last;
451                 }
452                 $itemnumber ||= $holding_branch_items->[0]->{itemnumber};
453             }
454             else {
455                 warn "No transport costs for $pickup_branch";
456             }
457         }
458
459         unless ($itemnumber) {
460             # not found yet, fall back to basics
461             if ($branches_to_use) {
462                 $pull_branches = $branches_to_use;
463             } else {
464                 $pull_branches = [keys %items_by_branch];
465             }
466             PULL_BRANCHES:
467             foreach my $branch (@$pull_branches) {
468                 my $holding_branch_items = $items_by_branch{$branch}
469                   or next;
470
471                 $holdingbranch ||= $branch;
472                 foreach my $item (@$holding_branch_items) {
473                     next if $pickup_branch ne $item->{homebranch};
474
475                     $itemnumber = $item->{itemnumber};
476                     $holdingbranch = $branch;
477                     last PULL_BRANCHES;
478                 }
479             }
480             $itemnumber ||= $items_by_branch{$holdingbranch}->[0]->{itemnumber}
481               if $holdingbranch;
482         }
483
484         if ($itemnumber) {
485             my $holding_branch_items = $items_by_branch{$holdingbranch}
486               or die "Have $itemnumber, $holdingbranch, but no items!";
487             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
488             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
489
490             $item_map{$itemnumber} = {
491                 borrowernumber => $request->{borrowernumber},
492                 biblionumber => $request->{biblionumber},
493                 holdingbranch => $holdingbranch,
494                 pickup_branch => $pickup_branch,
495                 item_level => 0,
496                 reservedate => $request->{reservedate},
497                 reservenotes => $request->{reservenotes},
498             };
499             $num_items_remaining--;
500         }
501     }
502     return \%item_map;
503 }
504
505 =head2 CreatePickListFromItemMap
506
507 =cut
508
509 sub CreatePicklistFromItemMap {
510     my $item_map = shift;
511
512     my $dbh = C4::Context->dbh;
513
514     my $sth_load=$dbh->prepare("
515         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
516                                     cardnumber,reservedate,title, itemcallnumber,
517                                     holdingbranch,pickbranch,notes, item_level_request)
518         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
519     ");
520
521     foreach my $itemnumber  (sort keys %$item_map) {
522         my $mapped_item = $item_map->{$itemnumber};
523         my $biblionumber = $mapped_item->{biblionumber};
524         my $borrowernumber = $mapped_item->{borrowernumber};
525         my $pickbranch = $mapped_item->{pickup_branch};
526         my $holdingbranch = $mapped_item->{holdingbranch};
527         my $reservedate = $mapped_item->{reservedate};
528         my $reservenotes = $mapped_item->{reservenotes};
529         my $item_level = $mapped_item->{item_level};
530
531         my $item = GetItem($itemnumber);
532         my $barcode = $item->{barcode};
533         my $itemcallnumber = $item->{itemcallnumber};
534
535         my $borrower = GetMember('borrowernumber'=>$borrowernumber);
536         my $cardnumber = $borrower->{'cardnumber'};
537         my $surname = $borrower->{'surname'};
538         my $firstname = $borrower->{'firstname'};
539         my $phone = $borrower->{'phone'};
540
541         my $bib = GetBiblioData($biblionumber);
542         my $title = $bib->{title};
543
544         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
545                            $cardnumber, $reservedate, $title, $itemcallnumber,
546                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
547     }
548 }
549
550 =head2 AddToHoldTargetMap
551
552 =cut
553
554 sub AddToHoldTargetMap {
555     my $item_map = shift;
556
557     my $dbh = C4::Context->dbh;
558
559     my $insert_sql = q(
560         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request)
561                                VALUES (?, ?, ?, ?, ?)
562     );
563     my $sth_insert = $dbh->prepare($insert_sql);
564
565     foreach my $itemnumber (keys %$item_map) {
566         my $mapped_item = $item_map->{$itemnumber};
567         $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
568                              $mapped_item->{holdingbranch}, $mapped_item->{item_level});
569     }
570 }
571
572 # Helper functions, not part of any interface
573
574 sub _trim {
575     return $_[0] unless $_[0];
576     $_[0] =~ s/^\s+//;
577     $_[0] =~ s/\s+$//;
578     $_[0];
579 }
580
581 sub load_branches_to_pull_from {
582     my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight")
583       or return;
584
585     my @branches_to_use = map _trim($_), split /,/, $static_branch_list;
586
587     @branches_to_use = shuffle(@branches_to_use) if  C4::Context->preference("RandomizeHoldsQueueWeight");
588
589     return \@branches_to_use;
590 }
591
592 sub least_cost_branch {
593
594     #$from - arrayref
595     my ($to, $from, $transport_cost_matrix) = @_;
596
597 # Nothing really spectacular: supply to branch, a list of potential from branches
598 # and find the minimum from - to value from the transport_cost_matrix
599     return $from->[0] if @$from == 1;
600
601     my ($least_cost, @branch);
602     foreach (@$from) {
603         my $cell = $transport_cost_matrix->{$to}{$_};
604         next if $cell->{disable_transfer};
605
606         my $cost = $cell->{cost};
607         next unless defined $cost; # XXX should this be reported?
608
609         unless (defined $least_cost) {
610             $least_cost = $cost;
611             push @branch, $_;
612             next;
613         }
614
615         next if $cost > $least_cost;
616
617         if ($cost == $least_cost) {
618             push @branch, $_;
619             next;
620         }
621
622         @branch = ($_);
623         $least_cost = $cost;
624     }
625
626     return $branch[0];
627
628     # XXX return a random @branch with minimum cost instead of the first one;
629     # return $branch[0] if @branch == 1;
630 }
631
632
633 1;