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