Bug 11810: Input fields in OPAC suggestion form are a bit short (Bootstrap)
[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         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     * it is not damaged (unless AllowHoldsOnDamagedItems is on)
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
334     my @params = ($biblionumber, $biblionumber);
335     if ($branches_to_use && @$branches_to_use) {
336         $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
337         push @params, @$branches_to_use;
338     }
339     my $sth = $dbh->prepare($items_query);
340     $sth->execute(@params);
341
342     my $itm = $sth->fetchall_arrayref({});
343     my @items = grep { ! scalar GetTransfers($_->{itemnumber}) } @$itm;
344     return [ grep {
345         my $rule = GetBranchItemRule($_->{homebranch}, $_->{itype});
346         $_->{holdallowed} = $rule->{holdallowed};
347     } @items ];
348 }
349
350 =head2 MapItemsToHoldRequests
351
352   MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
353
354 =cut
355
356 sub MapItemsToHoldRequests {
357     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
358
359     # handle trival cases
360     return unless scalar(@$hold_requests) > 0;
361     return unless scalar(@$available_items) > 0;
362
363     # identify item-level requests
364     my %specific_items_requested = map { $_->{itemnumber} => 1 }
365                                    grep { defined($_->{itemnumber}) }
366                                    @$hold_requests;
367
368     # group available items by itemnumber
369     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
370
371     # items already allocated
372     my %allocated_items = ();
373
374     # map of items to hold requests
375     my %item_map = ();
376
377     # figure out which item-level requests can be filled
378     my $num_items_remaining = scalar(@$available_items);
379     foreach my $request (@$hold_requests) {
380         last if $num_items_remaining == 0;
381
382         # is this an item-level request?
383         if (defined($request->{itemnumber})) {
384             # fill it if possible; if not skip it
385             if (exists $items_by_itemnumber{$request->{itemnumber}} and
386                 not exists $allocated_items{$request->{itemnumber}}) {
387                 $item_map{$request->{itemnumber}} = {
388                     borrowernumber => $request->{borrowernumber},
389                     biblionumber => $request->{biblionumber},
390                     holdingbranch =>  $items_by_itemnumber{$request->{itemnumber}}->{holdingbranch},
391                     pickup_branch => $request->{branchcode} || $request->{borrowerbranch},
392                     item_level => 1,
393                     reservedate => $request->{reservedate},
394                     reservenotes => $request->{reservenotes},
395                 };
396                 $allocated_items{$request->{itemnumber}}++;
397                 $num_items_remaining--;
398             }
399         } else {
400             # it's title-level request that will take up one item
401             $num_items_remaining--;
402         }
403     }
404
405     # group available items by branch
406     my %items_by_branch = ();
407     foreach my $item (@$available_items) {
408         next unless $item->{holdallowed};
409
410         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
411           unless exists $allocated_items{ $item->{itemnumber} };
412     }
413     return \%item_map unless keys %items_by_branch;
414
415     # now handle the title-level requests
416     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
417     my $pull_branches;
418     foreach my $request (@$hold_requests) {
419         last if $num_items_remaining == 0;
420         next if defined($request->{itemnumber}); # already handled these
421
422         # look for local match first
423         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
424         my ($itemnumber, $holdingbranch);
425
426         my $holding_branch_items = $items_by_branch{$pickup_branch};
427         if ( $holding_branch_items ) {
428             foreach my $item (@$holding_branch_items) {
429                 if ( $request->{borrowerbranch} eq $item->{homebranch} ) {
430                     $itemnumber = $item->{itemnumber};
431                     last;
432                 }
433             }
434             $holdingbranch = $pickup_branch;
435         }
436         elsif ($transport_cost_matrix) {
437             $pull_branches = [keys %items_by_branch];
438             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
439             if ( $holdingbranch ) {
440
441                 my $holding_branch_items = $items_by_branch{$holdingbranch};
442                 foreach my $item (@$holding_branch_items) {
443                     next if $request->{borrowerbranch} ne $item->{homebranch};
444
445                     $itemnumber = $item->{itemnumber};
446                     last;
447                 }
448             }
449             else {
450                 warn "No transport costs for $pickup_branch";
451             }
452         }
453
454         unless ($itemnumber) {
455             # not found yet, fall back to basics
456             if ($branches_to_use) {
457                 $pull_branches = $branches_to_use;
458             } else {
459                 $pull_branches = [keys %items_by_branch];
460             }
461             PULL_BRANCHES:
462             foreach my $branch (@$pull_branches) {
463                 my $holding_branch_items = $items_by_branch{$branch}
464                   or next;
465
466                 $holdingbranch ||= $branch;
467                 foreach my $item (@$holding_branch_items) {
468                     next if $pickup_branch ne $item->{homebranch};
469                     next if ( $item->{holdallowed} == 1 && $item->{homebranch} ne $request->{borrowerbranch} );
470
471                     $itemnumber = $item->{itemnumber};
472                     $holdingbranch = $branch;
473                     last PULL_BRANCHES;
474                 }
475             }
476
477             unless ( $itemnumber ) {
478                 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
479                     if ( $holdingbranch && ( $current_item->{holdallowed} == 2 || $request->{borrowerbranch} eq $current_item->{homebranch} ) ) {
480                         $itemnumber = $current_item->{itemnumber};
481                         last; # quit this loop as soon as we have a suitable item
482                     }
483                 }
484             }
485         }
486
487         if ($itemnumber) {
488             my $holding_branch_items = $items_by_branch{$holdingbranch}
489               or die "Have $itemnumber, $holdingbranch, but no items!";
490             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
491             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
492
493             $item_map{$itemnumber} = {
494                 borrowernumber => $request->{borrowernumber},
495                 biblionumber => $request->{biblionumber},
496                 holdingbranch => $holdingbranch,
497                 pickup_branch => $pickup_branch,
498                 item_level => 0,
499                 reservedate => $request->{reservedate},
500                 reservenotes => $request->{reservenotes},
501             };
502             $num_items_remaining--;
503         }
504     }
505     return \%item_map;
506 }
507
508 =head2 CreatePickListFromItemMap
509
510 =cut
511
512 sub CreatePicklistFromItemMap {
513     my $item_map = shift;
514
515     my $dbh = C4::Context->dbh;
516
517     my $sth_load=$dbh->prepare("
518         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
519                                     cardnumber,reservedate,title, itemcallnumber,
520                                     holdingbranch,pickbranch,notes, item_level_request)
521         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
522     ");
523
524     foreach my $itemnumber  (sort keys %$item_map) {
525         my $mapped_item = $item_map->{$itemnumber};
526         my $biblionumber = $mapped_item->{biblionumber};
527         my $borrowernumber = $mapped_item->{borrowernumber};
528         my $pickbranch = $mapped_item->{pickup_branch};
529         my $holdingbranch = $mapped_item->{holdingbranch};
530         my $reservedate = $mapped_item->{reservedate};
531         my $reservenotes = $mapped_item->{reservenotes};
532         my $item_level = $mapped_item->{item_level};
533
534         my $item = GetItem($itemnumber);
535         my $barcode = $item->{barcode};
536         my $itemcallnumber = $item->{itemcallnumber};
537
538         my $borrower = GetMember('borrowernumber'=>$borrowernumber);
539         my $cardnumber = $borrower->{'cardnumber'};
540         my $surname = $borrower->{'surname'};
541         my $firstname = $borrower->{'firstname'};
542         my $phone = $borrower->{'phone'};
543
544         my $bib = GetBiblioData($biblionumber);
545         my $title = $bib->{title};
546
547         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
548                            $cardnumber, $reservedate, $title, $itemcallnumber,
549                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
550     }
551 }
552
553 =head2 AddToHoldTargetMap
554
555 =cut
556
557 sub AddToHoldTargetMap {
558     my $item_map = shift;
559
560     my $dbh = C4::Context->dbh;
561
562     my $insert_sql = q(
563         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request)
564                                VALUES (?, ?, ?, ?, ?)
565     );
566     my $sth_insert = $dbh->prepare($insert_sql);
567
568     foreach my $itemnumber (keys %$item_map) {
569         my $mapped_item = $item_map->{$itemnumber};
570         $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
571                              $mapped_item->{holdingbranch}, $mapped_item->{item_level});
572     }
573 }
574
575 # Helper functions, not part of any interface
576
577 sub _trim {
578     return $_[0] unless $_[0];
579     $_[0] =~ s/^\s+//;
580     $_[0] =~ s/\s+$//;
581     $_[0];
582 }
583
584 sub load_branches_to_pull_from {
585     my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight")
586       or return;
587
588     my @branches_to_use = map _trim($_), split /,/, $static_branch_list;
589
590     @branches_to_use = shuffle(@branches_to_use) if  C4::Context->preference("RandomizeHoldsQueueWeight");
591
592     return \@branches_to_use;
593 }
594
595 sub least_cost_branch {
596
597     #$from - arrayref
598     my ($to, $from, $transport_cost_matrix) = @_;
599
600     # Nothing really spectacular: supply to branch, a list of potential from branches
601     # and find the minimum from - to value from the transport_cost_matrix
602     return $from->[0] if @$from == 1;
603
604     # If the pickup library is in the list of libraries to pull from,
605     # return that library right away, it is obviously the least costly
606     return ($to) if any { $_ eq $to } @$from;
607
608     my ($least_cost, @branch);
609     foreach (@$from) {
610         my $cell = $transport_cost_matrix->{$to}{$_};
611         next if $cell->{disable_transfer};
612
613         my $cost = $cell->{cost};
614         next unless defined $cost; # XXX should this be reported?
615
616         unless (defined $least_cost) {
617             $least_cost = $cost;
618             push @branch, $_;
619             next;
620         }
621
622         next if $cost > $least_cost;
623
624         if ($cost == $least_cost) {
625             push @branch, $_;
626             next;
627         }
628
629         @branch = ($_);
630         $least_cost = $cost;
631     }
632
633     return $branch[0];
634
635     # XXX return a random @branch with minimum cost instead of the first one;
636     # return $branch[0] if @branch == 1;
637 }
638
639
640 1;