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