Bug 30477: Add new UNIMARC installer translation files
[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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
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::Circulation qw( GetTransfers GetBranchItemRule );
28 use Koha::DateUtils qw( dt_from_string );
29 use Koha::Items;
30 use Koha::Patrons;
31 use Koha::Libraries;
32
33 use List::Util qw( shuffle );
34 use List::MoreUtils qw( any );
35
36 our (@ISA, @EXPORT_OK);
37 BEGIN {
38     require Exporter;
39     @ISA = qw(Exporter);
40     @EXPORT_OK = qw(
41         CreateQueue
42         GetHoldsQueueItems
43
44         TransportCostMatrix
45         UpdateTransportCostMatrix
46         GetPendingHoldRequestsForBib
47      );
48 }
49
50
51 =head1 FUNCTIONS
52
53 =head2 TransportCostMatrix
54
55   TransportCostMatrix();
56
57 Returns Transport Cost Matrix as a hashref <to branch code> => <from branch code> => cost
58
59 =cut
60
61 sub TransportCostMatrix {
62     my ( $params ) = @_;
63
64     my $dbh   = C4::Context->dbh;
65     my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} });
66
67     my $today = dt_from_string();
68     my %transport_cost_matrix;
69     foreach (@$transport_costs) {
70         my $from     = $_->{frombranch};
71         my $to       = $_->{tobranch};
72         my $cost     = $_->{cost};
73         my $disabled = $_->{disable_transfer};
74         $transport_cost_matrix{$to}{$from} = {
75             cost             => $cost,
76             disable_transfer => $disabled
77         };
78     }
79
80     return \%transport_cost_matrix;
81 }
82
83 =head2 UpdateTransportCostMatrix
84
85   UpdateTransportCostMatrix($records);
86
87 Updates full Transport Cost Matrix table. $records is an arrayref of records.
88 Records: { frombranch => <code>, tobranch => <code>, cost => <figure>, disable_transfer => <0,1> }
89
90 =cut
91
92 sub UpdateTransportCostMatrix {
93     my ($records) = @_;
94     my $dbh   = C4::Context->dbh;
95
96     my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)");
97
98     $dbh->do("DELETE FROM transport_cost");
99     foreach (@$records) {
100         my $cost = $_->{cost};
101         my $from = $_->{frombranch};
102         my $to = $_->{tobranch};
103         if ($_->{disable_transfer}) {
104             $cost ||= 0;
105         }
106         elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) {
107             warn  "Invalid $from -> $to cost $cost - must be a number >= 0, disabling";
108             $cost = 0;
109             $_->{disable_transfer} = 1;
110         }
111         $sth->execute( $from, $to, $cost, $_->{disable_transfer} ? 1 : 0 );
112     }
113 }
114
115 =head2 GetHoldsQueueItems
116
117   GetHoldsQueueItems({ branchlimit => $branch, itemtypeslimit =>  $itype, ccodeslimit => $ccode, locationslimit => $location );
118
119 Returns hold queue for a holding branch. If branch is omitted, then whole queue is returned
120
121 =cut
122
123 sub GetHoldsQueueItems {
124     my $params = shift;
125     my $dbh   = C4::Context->dbh;
126
127     my @bind_params = ();
128     my $query = q/SELECT tmp_holdsqueue.*, biblio.author, items.ccode, items.itype, biblioitems.itemtype, items.location,
129                          items.enumchron, items.cn_sort, biblioitems.publishercode,
130                          biblio.copyrightdate, biblio.subtitle, biblio.medium,
131                          biblio.part_number, biblio.part_name,
132                          biblioitems.publicationyear, biblioitems.pages, biblioitems.size,
133                          biblioitems.isbn, biblioitems.editionstatement, items.copynumber
134                   FROM tmp_holdsqueue
135                        JOIN biblio      USING (biblionumber)
136                   LEFT JOIN biblioitems USING (biblionumber)
137                   LEFT JOIN items       USING (  itemnumber)
138                   WHERE 1=1
139                 /;
140     if ($params->{branchlimit}) {
141         $query .="AND tmp_holdsqueue.holdingbranch = ? ";
142         push @bind_params, $params->{branchlimit};
143     }
144     if( $params->{itemtypeslimit} ) {
145         $query .=" AND items.itype = ? ";
146         push @bind_params, $params->{itemtypeslimit};
147     }
148     if( $params->{ccodeslimit} ) {
149         $query .=" AND items.ccode = ? ";
150         push @bind_params, $params->{ccodeslimit};
151     }
152     if( $params->{locationslimit} ) {
153         $query .=" AND items.location = ? ";
154         push @bind_params, $params->{locationslimit};
155     }
156     $query .= " ORDER BY ccode, location, cn_sort, author, title, pickbranch, reservedate";
157     my $sth = $dbh->prepare($query);
158     $sth->execute(@bind_params);
159     my $items = [];
160     while ( my $row = $sth->fetchrow_hashref ){
161         # return the bib-level or item-level itype per syspref
162         if (!C4::Context->preference('item-level_itypes')) {
163             $row->{itype} = $row->{itemtype};
164         }
165         delete $row->{itemtype};
166
167         push @$items, $row;
168     }
169     return $items;
170 }
171
172 =head2 CreateQueue
173
174   CreateQueue();
175
176 Top level function that turns reserves into tmp_holdsqueue and hold_fill_targets.
177
178 =cut
179
180 sub CreateQueue {
181     my $dbh   = C4::Context->dbh;
182
183     $dbh->do("DELETE FROM tmp_holdsqueue");  # clear the old table for new info
184     $dbh->do("DELETE FROM hold_fill_targets");
185
186     my $total_bibs            = 0;
187     my $total_requests        = 0;
188     my $total_available_items = 0;
189     my $num_items_mapped      = 0;
190
191     my $branches_to_use;
192     my $transport_cost_matrix;
193     my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix");
194     if ($use_transport_cost_matrix) {
195         $transport_cost_matrix = TransportCostMatrix();
196         unless (keys %$transport_cost_matrix) {
197             warn "UseTransportCostMatrix set to yes, but matrix not populated";
198             undef $transport_cost_matrix;
199         }
200     }
201
202     $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix);
203
204     my $bibs_with_pending_requests = GetBibsWithPendingHoldRequests();
205
206     foreach my $biblionumber (@$bibs_with_pending_requests) {
207         $total_bibs++;
208         my $hold_requests   = GetPendingHoldRequestsForBib($biblionumber);
209         my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_to_use);
210         $total_requests        += scalar(@$hold_requests);
211         $total_available_items += scalar(@$available_items);
212
213         my $item_map = MapItemsToHoldRequests($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix);
214         $item_map  or next;
215         my $item_map_size = scalar(keys %$item_map)
216           or next;
217
218         $num_items_mapped += $item_map_size;
219         CreatePicklistFromItemMap($item_map);
220         AddToHoldTargetMap($item_map);
221         if (($item_map_size < scalar(@$hold_requests  )) and
222             ($item_map_size < scalar(@$available_items))) {
223             # DOUBLE CHECK, but this is probably OK - unfilled item-level requests
224             # FIXME
225             #warn "unfilled requests for $biblionumber";
226             #warn Dumper($hold_requests), Dumper($available_items), Dumper($item_map);
227         }
228     }
229 }
230
231 =head2 GetBibsWithPendingHoldRequests
232
233   my $biblionumber_aref = GetBibsWithPendingHoldRequests();
234
235 Return an arrayref of the biblionumbers of all bibs
236 that have one or more unfilled hold requests.
237
238 =cut
239
240 sub GetBibsWithPendingHoldRequests {
241     my $dbh = C4::Context->dbh;
242
243     my $bib_query = "SELECT DISTINCT biblionumber
244                      FROM reserves
245                      WHERE found IS NULL
246                      AND priority > 0
247                      AND reservedate <= CURRENT_DATE()
248                      AND suspend = 0
249                      ";
250     my $sth = $dbh->prepare($bib_query);
251
252     $sth->execute();
253     my $biblionumbers = $sth->fetchall_arrayref();
254
255     return [ map { $_->[0] } @$biblionumbers ];
256 }
257
258 =head2 GetPendingHoldRequestsForBib
259
260   my $requests = GetPendingHoldRequestsForBib($biblionumber);
261
262 Returns an arrayref of hashrefs to pending, unfilled hold requests
263 on the bib identified by $biblionumber.  The following keys
264 are present in each hashref:
265
266     biblionumber
267     borrowernumber
268     itemnumber
269     priority
270     branchcode
271     reservedate
272     reservenotes
273     borrowerbranch
274
275 The arrayref is sorted in order of increasing priority.
276
277 =cut
278
279 sub GetPendingHoldRequestsForBib {
280     my $biblionumber = shift;
281
282     my $dbh = C4::Context->dbh;
283
284     my $request_query = "SELECT biblionumber, borrowernumber, itemnumber, priority, reserve_id, reserves.branchcode,
285                                 reservedate, reservenotes, borrowers.branchcode AS borrowerbranch, itemtype, item_level_hold
286                          FROM reserves
287                          JOIN borrowers USING (borrowernumber)
288                          WHERE biblionumber = ?
289                          AND found IS NULL
290                          AND priority > 0
291                          AND reservedate <= CURRENT_DATE()
292                          AND suspend = 0
293                          ORDER BY priority";
294     my $sth = $dbh->prepare($request_query);
295     $sth->execute($biblionumber);
296
297     my $requests = $sth->fetchall_arrayref({});
298     return $requests;
299
300 }
301
302 =head2 GetItemsAvailableToFillHoldRequestsForBib
303
304   my $available_items = GetItemsAvailableToFillHoldRequestsForBib($biblionumber, $branches_ar);
305
306 Returns an arrayref of items available to fill hold requests
307 for the bib identified by C<$biblionumber>.  An item is available
308 to fill a hold request if and only if:
309
310     * it is not on loan
311     * it is not withdrawn
312     * it is not marked notforloan
313     * it is not currently in transit
314     * it is not lost
315     * it is not sitting on the hold shelf
316     * it is not damaged (unless AllowHoldsOnDamagedItems is on)
317
318 =cut
319
320 sub GetItemsAvailableToFillHoldRequestsForBib {
321     my ($biblionumber, $branches_to_use) = @_;
322
323     my $dbh = C4::Context->dbh;
324     my $items_query = "SELECT itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype
325                        FROM items ";
326
327     if (C4::Context->preference('item-level_itypes')) {
328         $items_query .=   "LEFT JOIN itemtypes ON (itemtypes.itemtype = items.itype) ";
329     } else {
330         $items_query .=   "JOIN biblioitems USING (biblioitemnumber)
331                            LEFT JOIN itemtypes USING (itemtype) ";
332     }
333     $items_query .=   "WHERE items.notforloan = 0
334                        AND holdingbranch IS NOT NULL
335                        AND itemlost = 0
336                        AND withdrawn = 0";
337     $items_query .= "  AND damaged = 0" unless C4::Context->preference('AllowHoldsOnDamagedItems');
338     $items_query .= "  AND items.onloan IS NULL
339                        AND (itemtypes.notforloan IS NULL OR itemtypes.notforloan = 0)
340                        AND itemnumber NOT IN (
341                            SELECT itemnumber
342                            FROM reserves
343                            WHERE biblionumber = ?
344                            AND itemnumber IS NOT NULL
345                            AND (found IS NOT NULL OR priority = 0)
346                         )
347                        AND items.biblionumber = ?";
348
349     my @params = ($biblionumber, $biblionumber);
350     if ($branches_to_use && @$branches_to_use) {
351         $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")";
352         push @params, @$branches_to_use;
353     }
354     my $sth = $dbh->prepare($items_query);
355     $sth->execute(@params);
356
357     my $itm = $sth->fetchall_arrayref({});
358     my @items = grep { ! scalar GetTransfers($_->{itemnumber}) } @$itm;
359     return [ grep {
360         my $rule = GetBranchItemRule($_->{homebranch}, $_->{itype});
361         $_->{holdallowed} = $rule->{holdallowed};
362         $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy};
363     } @items ];
364 }
365
366 =head2 _checkHoldPolicy
367
368     _checkHoldPolicy($item, $request)
369
370     check if item agrees with hold policies
371
372 =cut
373
374 sub _checkHoldPolicy {
375     my ( $item, $request ) = @_;
376
377     return 0 unless $item->{holdallowed} ne 'not_allowed';
378
379     return 0
380       if $item->{holdallowed} eq 'from_home_library'
381       && $item->{homebranch} ne $request->{borrowerbranch};
382
383     return 0
384       if $item->{'holdallowed'} eq 'from_local_hold_group'
385       && !Koha::Libraries->find( $item->{homebranch} )
386               ->validate_hold_sibling( { branchcode => $request->{borrowerbranch} } );
387
388     my $hold_fulfillment_policy = $item->{hold_fulfillment_policy};
389
390     return 0
391       if $hold_fulfillment_policy eq 'holdgroup'
392       && !Koha::Libraries->find( $item->{homebranch} )
393             ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
394
395     return 0
396       if $hold_fulfillment_policy eq 'homebranch'
397       && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
398
399     return 0
400       if $hold_fulfillment_policy eq 'holdingbranch'
401       && $request->{branchcode} ne $item->{$hold_fulfillment_policy};
402
403     return 0
404       if $hold_fulfillment_policy eq 'patrongroup'
405       && !Koha::Libraries->find( $request->{borrowerbranch} )
406               ->validate_hold_sibling( { branchcode => $request->{branchcode} } );
407
408     return 1;
409
410 }
411
412 =head2 MapItemsToHoldRequests
413
414   MapItemsToHoldRequests($hold_requests, $available_items, $branches, $transport_cost_matrix)
415
416 =cut
417
418 sub MapItemsToHoldRequests {
419     my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_;
420
421     # handle trival cases
422     return unless scalar(@$hold_requests) > 0;
423     return unless scalar(@$available_items) > 0;
424
425     # identify item-level requests
426     my %specific_items_requested = map { $_->{itemnumber} => 1 }
427                                    grep { defined($_->{itemnumber}) }
428                                    @$hold_requests;
429
430     map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items;
431     my $libraries = {};
432     map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list;
433
434     # group available items by itemnumber
435     my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items;
436
437     # items already allocated
438     my %allocated_items = ();
439
440     # map of items to hold requests
441     my %item_map = ();
442
443     # figure out which item-level requests can be filled
444     my $num_items_remaining = scalar(@$available_items);
445
446     # Look for Local Holds Priority matches first
447     if ( C4::Context->preference('LocalHoldsPriority') ) {
448         my $LocalHoldsPriorityPatronControl =
449           C4::Context->preference('LocalHoldsPriorityPatronControl');
450         my $LocalHoldsPriorityItemControl =
451           C4::Context->preference('LocalHoldsPriorityItemControl');
452
453         foreach my $request (@$hold_requests) {
454             last if $num_items_remaining == 0;
455             my $patron = Koha::Patrons->find($request->{borrowernumber});
456             next if $patron->category->exclude_from_local_holds_priority;
457
458             my $local_hold_match;
459             foreach my $item (@$available_items) {
460                 next if $item->{_object}->exclude_from_local_holds_priority;
461
462                 next unless _checkHoldPolicy($item, $request);
463
464                 next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber};
465
466                 next unless $item->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
467
468                 my $local_holds_priority_item_branchcode =
469                   $item->{$LocalHoldsPriorityItemControl};
470
471                 my $local_holds_priority_patron_branchcode =
472                   ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
473                   ? $request->{branchcode}
474                   : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
475                   ? $request->{borrowerbranch}
476                   : undef;
477
478                 $local_hold_match =
479                   $local_holds_priority_item_branchcode eq
480                   $local_holds_priority_patron_branchcode;
481
482                 if ($local_hold_match) {
483                     if ( exists $items_by_itemnumber{ $item->{itemnumber} }
484                         and not exists $allocated_items{ $item->{itemnumber} }
485                         and not $request->{allocated})
486                     {
487                         $item_map{ $item->{itemnumber} } = {
488                             borrowernumber => $request->{borrowernumber},
489                             biblionumber   => $request->{biblionumber},
490                             holdingbranch  => $item->{holdingbranch},
491                             pickup_branch  => $request->{branchcode}
492                               || $request->{borrowerbranch},
493                             reserve_id   => $request->{reserve_id},
494                             item_level   => $request->{item_level_hold},
495                             reservedate  => $request->{reservedate},
496                             reservenotes => $request->{reservenotes},
497                         };
498                         $allocated_items{ $item->{itemnumber} }++;
499                         $request->{allocated} = 1;
500                         $num_items_remaining--;
501                     }
502                 }
503             }
504         }
505     }
506
507     foreach my $request (@$hold_requests) {
508         last if $num_items_remaining == 0;
509         next if $request->{allocated};
510
511         # is this an item-level request?
512         if (defined($request->{itemnumber})) {
513             # fill it if possible; if not skip it
514             if (
515                     exists $items_by_itemnumber{ $request->{itemnumber} }
516                 and not exists $allocated_items{ $request->{itemnumber} }
517                 and  _checkHoldPolicy($items_by_itemnumber{ $request->{itemnumber} }, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
518                 and ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
519                     || $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} )
520
521                 and $items_by_itemnumber{ $request->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } )
522
523               )
524             {
525
526                 $item_map{ $request->{itemnumber} } = {
527                     borrowernumber => $request->{borrowernumber},
528                     biblionumber   => $request->{biblionumber},
529                     holdingbranch  => $items_by_itemnumber{ $request->{itemnumber} }->{holdingbranch},
530                     pickup_branch  => $request->{branchcode} || $request->{borrowerbranch},
531                     reserve_id     => $request->{reserve_id},
532                     item_level     => $request->{item_level_hold},
533                     reservedate    => $request->{reservedate},
534                     reservenotes   => $request->{reservenotes},
535                 };
536                 $allocated_items{ $request->{itemnumber} }++;
537                 $num_items_remaining--;
538             }
539         } else {
540             # it's title-level request that will take up one item
541             $num_items_remaining--;
542         }
543     }
544
545     # group available items by branch
546     my %items_by_branch = ();
547     foreach my $item (@$available_items) {
548         next unless $item->{holdallowed} ne 'not_allowed';
549
550         push @{ $items_by_branch{ $item->{holdingbranch} } }, $item
551           unless exists $allocated_items{ $item->{itemnumber} };
552     }
553     return \%item_map unless keys %items_by_branch;
554
555     # now handle the title-level requests
556     $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items);
557     my $pull_branches;
558     foreach my $request (@$hold_requests) {
559         last if $num_items_remaining == 0;
560         next if $request->{allocated};
561         next if defined($request->{itemnumber}); # already handled these
562
563         # look for local match first
564         my $pickup_branch = $request->{branchcode} || $request->{borrowerbranch};
565         my ($itemnumber, $holdingbranch);
566
567         my $holding_branch_items = $items_by_branch{$pickup_branch};
568         if ( $holding_branch_items ) {
569             foreach my $item (@$holding_branch_items) {
570                 next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
571
572                 if (
573                     $request->{borrowerbranch} eq $item->{homebranch}
574                     && _checkHoldPolicy($item, $request) # Don't fill item level holds that contravene the hold pickup policy at this time
575                     && ( !$request->{itemtype} # If hold itemtype is set, item's itemtype must match
576                         || ( $request->{itemnumber} && ( $items_by_itemnumber{ $request->{itemnumber} }->{itype} eq $request->{itemtype} ) ) )
577                   )
578                 {
579                     $itemnumber = $item->{itemnumber};
580                     last;
581                 }
582             }
583             $holdingbranch = $pickup_branch;
584         }
585         elsif ($transport_cost_matrix) {
586             $pull_branches = [keys %items_by_branch];
587             $holdingbranch = least_cost_branch( $pickup_branch, $pull_branches, $transport_cost_matrix );
588             if ( $holdingbranch ) {
589
590                 my $holding_branch_items = $items_by_branch{$holdingbranch};
591                 foreach my $item (@$holding_branch_items) {
592                     next if $request->{borrowerbranch} ne $item->{homebranch};
593                     next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
594
595                     # Don't fill item level holds that contravene the hold pickup policy at this time
596                     next unless _checkHoldPolicy($item, $request);
597
598                     # If hold itemtype is set, item's itemtype must match
599                     next unless ( !$request->{itemtype}
600                         || $item->{itype} eq $request->{itemtype} );
601
602                     $itemnumber = $item->{itemnumber};
603                     last;
604                 }
605             }
606             else {
607                 next;
608             }
609         }
610
611         unless ($itemnumber) {
612             # not found yet, fall back to basics
613             if ($branches_to_use) {
614                 $pull_branches = $branches_to_use;
615             } else {
616                 $pull_branches = [keys %items_by_branch];
617             }
618
619             # Try picking items where the home and pickup branch match first
620             PULL_BRANCHES:
621             foreach my $branch (@$pull_branches) {
622                 my $holding_branch_items = $items_by_branch{$branch}
623                   or next;
624
625                 $holdingbranch ||= $branch;
626                 foreach my $item (@$holding_branch_items) {
627                     next if $pickup_branch ne $item->{homebranch};
628                     next unless _checkHoldPolicy($item, $request);
629                     next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
630
631                     # Don't fill item level holds that contravene the hold pickup policy at this time
632                     next unless $item->{hold_fulfillment_policy} eq 'any'
633                         || $request->{branchcode} eq $item->{ $item->{hold_fulfillment_policy} };
634
635                     # If hold itemtype is set, item's itemtype must match
636                     next unless ( !$request->{itemtype}
637                         || $item->{itype} eq $request->{itemtype} );
638
639                     $itemnumber = $item->{itemnumber};
640                     $holdingbranch = $branch;
641                     last PULL_BRANCHES;
642                 }
643             }
644
645             # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight
646             unless ( $itemnumber || !$holdingbranch) {
647                 foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) {
648                     next unless _checkHoldPolicy($current_item, $request); # Don't fill item level holds that contravene the hold pickup policy at this time
649
650                     # If hold itemtype is set, item's itemtype must match
651                     next unless ( !$request->{itemtype}
652                         || $current_item->{itype} eq $request->{itemtype} );
653
654                     next unless $items_by_itemnumber{ $current_item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
655
656                     $itemnumber = $current_item->{itemnumber};
657                     last; # quit this loop as soon as we have a suitable item
658                 }
659             }
660
661             # Now try for items for any item that can fill this hold
662             unless ( $itemnumber ) {
663                 PULL_BRANCHES2:
664                 foreach my $branch (@$pull_branches) {
665                     my $holding_branch_items = $items_by_branch{$branch}
666                       or next;
667
668                     foreach my $item (@$holding_branch_items) {
669                         # Don't fill item level holds that contravene the hold pickup policy at this time
670                         next unless _checkHoldPolicy($item, $request);
671
672                         # If hold itemtype is set, item's itemtype must match
673                         next unless ( !$request->{itemtype}
674                             || $item->{itype} eq $request->{itemtype} );
675
676                         next unless $items_by_itemnumber{ $item->{itemnumber} }->{_object}->can_be_transferred( { to => $libraries->{ $request->{branchcode} } } );
677
678                         $itemnumber = $item->{itemnumber};
679                         $holdingbranch = $branch;
680                         last PULL_BRANCHES2;
681                     }
682                 }
683             }
684         }
685
686         if ($itemnumber) {
687             my $holding_branch_items = $items_by_branch{$holdingbranch}
688               or die "Have $itemnumber, $holdingbranch, but no items!";
689             @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items;
690             delete $items_by_branch{$holdingbranch} unless @$holding_branch_items;
691
692             $item_map{$itemnumber} = {
693                 borrowernumber => $request->{borrowernumber},
694                 biblionumber => $request->{biblionumber},
695                 holdingbranch => $holdingbranch,
696                 pickup_branch => $pickup_branch,
697                 reserve_id => $request->{reserve_id},
698                 item_level => $request->{item_level_hold},
699                 reservedate => $request->{reservedate},
700                 reservenotes => $request->{reservenotes},
701             };
702             $num_items_remaining--;
703         }
704     }
705     return \%item_map;
706 }
707
708 =head2 CreatePickListFromItemMap
709
710 =cut
711
712 sub CreatePicklistFromItemMap {
713     my $item_map = shift;
714
715     my $dbh = C4::Context->dbh;
716
717     my $sth_load=$dbh->prepare("
718         INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber,
719                                     cardnumber,reservedate,title, itemcallnumber,
720                                     holdingbranch,pickbranch,notes, item_level_request)
721         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
722     ");
723
724     foreach my $itemnumber  (sort keys %$item_map) {
725         my $mapped_item = $item_map->{$itemnumber};
726         my $biblionumber = $mapped_item->{biblionumber};
727         my $borrowernumber = $mapped_item->{borrowernumber};
728         my $pickbranch = $mapped_item->{pickup_branch};
729         my $holdingbranch = $mapped_item->{holdingbranch};
730         my $reservedate = $mapped_item->{reservedate};
731         my $reservenotes = $mapped_item->{reservenotes};
732         my $item_level = $mapped_item->{item_level};
733
734         my $item = Koha::Items->find($itemnumber);
735         my $barcode = $item->barcode;
736         my $itemcallnumber = $item->itemcallnumber;
737
738         my $patron = Koha::Patrons->find( $borrowernumber );
739         my $cardnumber = $patron->cardnumber;
740         my $surname = $patron->surname;
741         my $firstname = $patron->firstname;
742         my $phone = $patron->phone;
743
744         my $biblio = Koha::Biblios->find( $biblionumber );
745         my $title = $biblio->title;
746
747         $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber,
748                            $cardnumber, $reservedate, $title, $itemcallnumber,
749                            $holdingbranch, $pickbranch, $reservenotes, $item_level);
750     }
751 }
752
753 =head2 AddToHoldTargetMap
754
755 =cut
756
757 sub AddToHoldTargetMap {
758     my $item_map = shift;
759
760     my $dbh = C4::Context->dbh;
761
762     my $insert_sql = q(
763         INSERT INTO hold_fill_targets (borrowernumber, biblionumber, itemnumber, source_branchcode, item_level_request, reserve_id)
764                                VALUES (?, ?, ?, ?, ?, ?)
765     );
766     my $sth_insert = $dbh->prepare($insert_sql);
767
768     foreach my $itemnumber (keys %$item_map) {
769         my $mapped_item = $item_map->{$itemnumber};
770         $sth_insert->execute($mapped_item->{borrowernumber}, $mapped_item->{biblionumber}, $itemnumber,
771                              $mapped_item->{holdingbranch}, $mapped_item->{item_level}, $mapped_item->{reserve_id});
772     }
773 }
774
775 # Helper functions, not part of any interface
776
777 sub _trim {
778     return $_[0] unless $_[0];
779     $_[0] =~ s/^\s+//;
780     $_[0] =~ s/\s+$//;
781     $_[0];
782 }
783
784 sub load_branches_to_pull_from {
785     my $use_transport_cost_matrix = shift;
786
787     my @branches_to_use;
788
789     unless ( $use_transport_cost_matrix ) {
790         my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight");
791         @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list )
792           if $static_branch_list;
793     }
794
795     @branches_to_use =
796       Koha::Database->new()->schema()->resultset('Branch')
797       ->get_column('branchcode')->all()
798       unless (@branches_to_use);
799
800     @branches_to_use = shuffle(@branches_to_use)
801       if C4::Context->preference("RandomizeHoldsQueueWeight");
802
803     my $today = dt_from_string();
804     if ( C4::Context->preference('HoldsQueueSkipClosed') ) {
805         @branches_to_use = grep {
806             !Koha::Calendar->new( branchcode => $_ )
807               ->is_holiday( $today )
808         } @branches_to_use;
809     }
810
811     return \@branches_to_use;
812 }
813
814 sub least_cost_branch {
815
816     #$from - arrayref
817     my ($to, $from, $transport_cost_matrix) = @_;
818
819     # Nothing really spectacular: supply to branch, a list of potential from branches
820     # and find the minimum from - to value from the transport_cost_matrix
821     return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 );
822
823     # If the pickup library is in the list of libraries to pull from,
824     # return that library right away, it is obviously the least costly
825     return ($to) if any { $_ eq $to } @$from;
826
827     my ($least_cost, @branch);
828     foreach (@$from) {
829         my $cell = $transport_cost_matrix->{$to}{$_};
830         next if $cell->{disable_transfer};
831
832         my $cost = $cell->{cost};
833         next unless defined $cost; # XXX should this be reported?
834
835         unless (defined $least_cost) {
836             $least_cost = $cost;
837             push @branch, $_;
838             next;
839         }
840
841         next if $cost > $least_cost;
842
843         if ($cost == $least_cost) {
844             push @branch, $_;
845             next;
846         }
847
848         @branch = ($_);
849         $least_cost = $cost;
850     }
851
852     return $branch[0];
853
854     # XXX return a random @branch with minimum cost instead of the first one;
855     # return $branch[0] if @branch == 1;
856 }
857
858
859 1;