Bug 10270: Fix shebang
[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.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         push @$items, $row;
145     }
146     return $items;
147 }
148
149 =head2 CreateQueue
150
151   CreateQueue();
152
153 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
154
155 =cut
156
157 sub CreateQueue {
158     my $dbh   = C4::Context->dbh;
159
160     $dbh->do("DELETE FROM tmp_holdsqueue");  # clear the old table for new info
161     $dbh->do("DELETE FROM hold_fill_targets");
162
163     my $total_bibs            = 0;
164     my $total_requests        = 0;
165     my $total_available_items = 0;
166     my $num_items_mapped      = 0;
167
168     my $branches_to_use;
169     my $transport_cost_matrix;
170     my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
171     if ($use_transport_cost_matrix) {
172         $transport_cost_matrix = TransportCostMatrix();
173         unless (keys %$transport_cost_matrix) {
174             warn "UseTransportCostMatrix set to yes, but matrix not populated";
175             undef $transport_cost_matrix;
176         }
177     }
178     unless ($transport_cost_matrix) {
179         $branches_to_use = load_branches_to_pull_from();
180     }
181
182     my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
183
184     foreach my $biblionumber (@$bibs_with_pending_requests) {
185         $total_bibs++;
186         my $hold_requests   = GetPendingHoldRequestsForBib($biblionumber);
187         my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_to_use);
188         $total_requests        += scalar(@$hold_requests);
189         $total_available_items += scalar(@$available_items);
190
191         my $item_map = MapItemsToHoldRequests($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix);
192         $item_map  or next;
193         my $item_map_size = scalar(keys %$item_map)
194           or next;
195
196         $num_items_mapped += $item_map_size;
197         CreatePicklistFromItemMap($item_map);
198         AddToHoldTargetMap($item_map);
199         if (($item_map_size < scalar(@$hold_requests  )) and
200             ($item_map_size < scalar(@$available_items))) {
201             # DOUBLE CHECK, but this is probably OK - unfilled item-level requests
202             # FIXME
203             #warn "unfilled requests for $biblionumber";
204             #warn Dumper($hold_requests), Dumper($available_items), Dumper($item_map);
205         }
206     }
207 }
208
209 =head2 GetBibsWithPendingHoldRequests
210
211   my $biblionumber_aref = GetBibsWithPendingHoldRequests();
212
213 Return an arrayref of the biblionumbers of all bibs
214 that have one or more unfilled hold requests.
215
216 =cut
217
218 sub GetBibsWithPendingHoldRequests {
219     my $dbh = C4::Context->dbh;
220
221     my $bib_query = "SELECT DISTINCT biblionumber
222                      FROM reserves
223                      WHERE found IS NULL
224                      AND priority > 0
225                      AND reservedate <= CURRENT_DATE()
226                      AND suspend = 0
227                      ";
228     my $sth = $dbh->prepare($bib_query);
229
230     $sth->execute();
231     my $biblionumbers = $sth->fetchall_arrayref();
232
233     return [ map { $_->[0] } @$biblionumbers ];
234 }
235
236 =head2 GetPendingHoldRequestsForBib
237
238   my $requests = GetPendingHoldRequestsForBib($biblionumber);
239
240 Returns an arrayref of hashrefs to pending, unfilled hold requests
241 on the bib identified by $biblionumber.  The following keys
242 are present in each hashref:
243
244     biblionumber
245     borrowernumber
246     itemnumber
247     priority
248     branchcode
249     reservedate
250     reservenotes
251     borrowerbranch
252
253 The arrayref is sorted in order of increasing priority.
254
255 =cut
256
257 sub GetPendingHoldRequestsForBib {
258     my $biblionumber = shift;
259
260     my $dbh = C4::Context->dbh;
261
262     my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserves.branchcode,
263                                 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch
264                          FROM reserves
265                          JOIN borrowers USING (borrowernumber)
266                          WHERE biblionumber = ?
267                          AND found IS NULL
268                          AND priority > 0
269                          AND reservedate <= CURRENT_DATE()
270                          AND suspend = 0
271                          ORDER BY priority";
272     my $sth = $dbh->prepare($request_query);
273     $sth->execute($biblionumber);
274
275     my $requests = $sth->fetchall_arrayref({});
276     return $requests;
277
278 }
279
280 =head2 GetItemsAvailableToFillHoldRequestsForBib
281
282   my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
283
284 Returns an arrayref of items available to fill hold requests
285 for the bib identified by C<$biblionumber>.  An item is available
286 to fill a hold request if and only if:
287
288     * it is not on loan
289     * it is not withdrawn
290     * it is not marked notforloan
291     * it is not currently in transit
292     * it is not lost
293     * it is not sitting on the hold shelf
294
295 =cut
296
297 sub GetItemsAvailableToFillHoldRequestsForBib {
298     my ($biblionumber, $branches_to_use) = @_;
299
300     my $dbh = C4::Context->dbh;
301     my $items_query = "SELECT itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
302                        FROM items ";
303
304     if (C4::Context->preference('item-level_itypes')) {
305         $items_query .=   "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
306     } else {
307         $items_query .=   "JOIN biblioitems USING (biblioitemnumber)
308                            LEFT JOIN itemtypes USING (itemtype) ";
309     }
310     $items_query .=   "WHERE items.notforloan = 0
311                        AND holdingbranch IS NOT NULL
312                        AND itemlost = 0
313                        AND wthdrawn = 0";
314     $items_query .= "  AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
315     $items_query .= "  AND items.onloan IS NULL
316                        AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
317                        AND itemnumber NOT IN (
318                            SELECT itemnumber
319                            FROM reserves
320                            WHERE biblionumber = ?
321                            AND itemnumber IS NOT NULL
322                            AND (found IS NOT NULL OR priority = 0)
323                         )
324                        AND items.biblionumber = ?";
325     $items_query .=  " AND damaged = 0 "
326       unless C4::Context->preference('AllowHoldsOnDamagedItems');
327
328     my @params = ($biblionumber, $biblionumber);
329     if ($branches_to_use && @$branches_to_use) {
330         $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
331         push @params, @$branches_to_use;
332     }
333     my $sth = $dbh->prepare($items_query);
334     $sth->execute(@params);
335
336     my $itm = $sth->fetchall_arrayref({});
337     my @items = grep { ! scalar GetTransfers($_->{itemnumber}) } @$itm;
338     return [ grep {
339         my $rule = GetBranchItemRule($_->{homebranch}, $_->{itype});
340         $_->{holdallowed} = $rule->{holdallowed} != 0
341     } @items ];
342 }
343
344 =head2 MapItemsToHoldRequests
345
346   MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
347
348 =cut
349
350 sub MapItemsToHoldRequests {
351     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
352
353     # handle trival cases
354     return unless scalar(@$hold_requests) > 0;
355     return unless scalar(@$available_items) > 0;
356
357     my $automatic_return = C4::Context->preference("AutomaticItemReturn");
358
359     # identify item-level requests
360     my %specific_items_requested = map { $_->{itemnumber} => 1 }
361                                    grep { defined($_->{itemnumber}) }
362                                    @$hold_requests;
363
364     # group available items by itemnumber
365     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
366
367     # items already allocated
368     my %allocated_items = ();
369
370     # map of items to hold requests
371     my %item_map = ();
372
373     # figure out which item-level requests can be filled
374     my $num_items_remaining = scalar(@$available_items);
375     foreach my $request (@$hold_requests) {
376         last if $num_items_remaining == 0;
377
378         # is this an item-level request?
379         if (defined($request->{itemnumber})) {
380             # fill it if possible; if not skip it
381             if (exists $items_by_itemnumber{$request->{itemnumber}} and
382                 not exists $allocated_items{$request->{itemnumber}}) {
383                 $item_map{$request->{itemnumber}} = {
384                     borrowernumber => $request->{borrowernumber},
385                     biblionumber => $request->{biblionumber},
386                     holdingbranch =>  $items_by_itemnumber{$request->{itemnumber}}->{holdingbranch},
387                     pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
388                     item_level => 1,
389                     reservedate => $request->{reservedate},
390                     reservenotes => $request->{reservenotes},
391                 };
392                 $allocated_items{$request->{itemnumber}}++;
393                 $num_items_remaining--;
394             }
395         } else {
396             # it's title-level request that will take up one item
397             $num_items_remaining--;
398         }
399     }
400
401     # group available items by branch
402     my %items_by_branch = ();
403     foreach my $item (@$available_items) {
404         next unless $item->{holdallowed};
405
406         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
407           unless exists $allocated_items{ $item->{itemnumber} };
408     }
409     return unless keys %items_by_branch;
410
411     # now handle the title-level requests
412     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
413     my $pull_branches;
414     foreach my $request (@$hold_requests) {
415         last if $num_items_remaining == 0;
416         next if defined($request->{itemnumber}); # already handled these
417
418         # look for local match first
419         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
420         my ($itemnumber, $holdingbranch);
421
422         my $holding_branch_items = $automatic_return ? undef : $items_by_branch{$pickup_branch};
423         if ( $holding_branch_items ) {
424             foreach my $item (@$holding_branch_items) {
425                 if ( $request->{borrowerbranch} eq $item->{homebranch} ) {
426                     $itemnumber = $item->{itemnumber};
427                     last;
428                 }
429             }
430             $holdingbranch = $pickup_branch;
431             $itemnumber ||= $holding_branch_items->[0]->{itemnumber};
432         }
433         elsif ($transport_cost_matrix) {
434             $pull_branches = [keys %items_by_branch];
435             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
436             if ( $holdingbranch ) {
437
438                 my $holding_branch_items = $items_by_branch{$holdingbranch};
439                 foreach my $item (@$holding_branch_items) {
440                     next if $request->{borrowerbranch} ne $item->{homebranch};
441
442                     $itemnumber = $item->{itemnumber};
443                     last;
444                 }
445                 $itemnumber ||= $holding_branch_items->[0]->{itemnumber};
446             }
447             else {
448                 warn "No transport costs for $pickup_branch";
449             }
450         }
451
452         unless ($itemnumber) {
453             # not found yet, fall back to basics
454             if ($branches_to_use) {
455                 $pull_branches = $branches_to_use;
456             } else {
457                 $pull_branches = [keys %items_by_branch];
458             }
459             PULL_BRANCHES:
460             foreach my $branch (@$pull_branches) {
461                 my $holding_branch_items = $items_by_branch{$branch}
462                   or next;
463
464                 $holdingbranch ||= $branch;
465                 foreach my $item (@$holding_branch_items) {
466                     next if $pickup_branch ne $item->{homebranch};
467
468                     $itemnumber = $item->{itemnumber};
469                     $holdingbranch = $branch;
470                     last PULL_BRANCHES;
471                 }
472             }
473             $itemnumber ||= $items_by_branch{$holdingbranch}->[0]->{itemnumber}
474               if $holdingbranch;
475         }
476
477         if ($itemnumber) {
478             my $holding_branch_items = $items_by_branch{$holdingbranch}
479               or die "Have $itemnumber, $holdingbranch, but no items!";
480             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
481             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
482
483             $item_map{$itemnumber} = {
484                 borrowernumber => $request->{borrowernumber},
485                 biblionumber => $request->{biblionumber},
486                 holdingbranch => $holdingbranch,
487                 pickup_branch => $pickup_branch,
488                 item_level => 0,
489                 reservedate => $request->{reservedate},
490                 reservenotes => $request->{reservenotes},
491             };
492             $num_items_remaining--;
493         }
494     }
495     return \%item_map;
496 }
497
498 =head2 CreatePickListFromItemMap
499
500 =cut
501
502 sub CreatePicklistFromItemMap {
503     my $item_map = shift;
504
505     my $dbh = C4::Context->dbh;
506
507     my $sth_load=$dbh->prepare("
508         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
509                                     cardnumber,reservedate,title, itemcallnumber,
510                                     holdingbranch,pickbranch,notes, item_level_request)
511         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
512     ");
513
514     foreach my $itemnumber  (sort keys %$item_map) {
515         my $mapped_item = $item_map->{$itemnumber};
516         my $biblionumber = $mapped_item->{biblionumber};
517         my $borrowernumber = $mapped_item->{borrowernumber};
518         my $pickbranch = $mapped_item->{pickup_branch};
519         my $holdingbranch = $mapped_item->{holdingbranch};
520         my $reservedate = $mapped_item->{reservedate};
521         my $reservenotes = $mapped_item->{reservenotes};
522         my $item_level = $mapped_item->{item_level};
523
524         my $item = GetItem($itemnumber);
525         my $barcode = $item->{barcode};
526         my $itemcallnumber = $item->{itemcallnumber};
527
528         my $borrower = GetMember('borrowernumber'=>$borrowernumber);
529         my $cardnumber = $borrower->{'cardnumber'};
530         my $surname = $borrower->{'surname'};
531         my $firstname = $borrower->{'firstname'};
532         my $phone = $borrower->{'phone'};
533
534         my $bib = GetBiblioData($biblionumber);
535         my $title = $bib->{title};
536
537         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
538                            $cardnumber, $reservedate, $title, $itemcallnumber,
539                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
540     }
541 }
542
543 =head2 AddToHoldTargetMap
544
545 =cut
546
547 sub AddToHoldTargetMap {
548     my $item_map = shift;
549
550     my $dbh = C4::Context->dbh;
551
552     my $insert_sql = q(
553         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request)
554                                VALUES (?, ?, ?, ?, ?)
555     );
556     my $sth_insert = $dbh->prepare($insert_sql);
557
558     foreach my $itemnumber (keys %$item_map) {
559         my $mapped_item = $item_map->{$itemnumber};
560         $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
561                              $mapped_item->{holdingbranch}, $mapped_item->{item_level});
562     }
563 }
564
565 # Helper functions, not part of any interface
566
567 sub _trim {
568     return $_[0] unless $_[0];
569     $_[0] =~ s/^\s+//;
570     $_[0] =~ s/\s+$//;
571     $_[0];
572 }
573
574 sub load_branches_to_pull_from {
575     my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight")
576       or return;
577
578     my @branches_to_use = map _trim($_), split /,/, $static_branch_list;
579
580     @branches_to_use = shuffle(@branches_to_use) if  C4::Context->preference("RandomizeHoldsQueueWeight");
581
582     return \@branches_to_use;
583 }
584
585 sub least_cost_branch {
586
587     #$from - arrayref
588     my ($to, $from, $transport_cost_matrix) = @_;
589
590 # Nothing really spectacular: supply to branch, a list of potential from branches
591 # and find the minimum from - to value from the transport_cost_matrix
592     return $from->[0] if @$from == 1;
593
594     my ($least_cost, @branch);
595     foreach (@$from) {
596         my $cell = $transport_cost_matrix->{$to}{$_};
597         next if $cell->{disable_transfer};
598
599         my $cost = $cell->{cost};
600         next unless defined $cost; # XXX should this be reported?
601
602         unless (defined $least_cost) {
603             $least_cost = $cost;
604             push @branch, $_;
605             next;
606         }
607
608         next if $cost > $least_cost;
609
610         if ($cost == $least_cost) {
611             push @branch, $_;
612             next;
613         }
614
615         @branch = ($_);
616         $least_cost = $cost;
617     }
618
619     return $branch[0];
620
621     # XXX return a random @branch with minimum cost instead of the first one;
622     # return $branch[0] if @branch == 1;
623 }
624
625
626 1;