Bug 11132: don't clear the results list upon adding a biblio to a list
[koha.git] / tools / inventory.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2009 Biblibre S.A
4 #                                         John Soros <john.soros@biblibre.com>
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use strict;
22 use warnings;
23
24 #need to open cgi and get the fh before anything else opens a new cgi context (see C4::Auth)
25 use CGI;
26 my $input = CGI->new;
27 my $uploadbarcodes = $input->param('uploadbarcodes');
28
29 use C4::Auth;
30 use C4::Context;
31 use C4::Output;
32 use C4::Biblio;
33 use C4::Items;
34 use C4::Koha;
35 use C4::Branch; # GetBranches
36 use C4::Circulation;
37 use C4::Reports::Guided;    #_get_column_defs
38 use C4::Charset;
39 use Koha::DateUtils;
40 use List::MoreUtils qw( none );
41
42
43 my $minlocation=$input->param('minlocation') || '';
44 my $maxlocation=$input->param('maxlocation');
45 $maxlocation=$minlocation.'Z' unless ( $maxlocation || ! $minlocation );
46 my $location=$input->param('location') || '';
47 my $itemtype=$input->param('itemtype'); # FIXME note, template does not currently supply this
48 my $ignoreissued=$input->param('ignoreissued');
49 my $datelastseen = $input->param('datelastseen');
50 my $markseen = $input->param('markseen');
51 my $branchcode = $input->param('branchcode') || '';
52 my $branch     = $input->param('branch');
53 my $op         = $input->param('op');
54 my $compareinv2barcd = $input->param('compareinv2barcd');
55
56 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
57     {   template_name   => "tools/inventory.tt",
58         query           => $input,
59         type            => "intranet",
60         authnotrequired => 0,
61         flagsrequired   => { tools => 'inventory' },
62         debug           => 1,
63     }
64 );
65
66
67 my $branches = GetBranches();
68 my @branch_loop;
69 for my $branch_hash (keys %$branches) {
70     push @branch_loop, {value => "$branch_hash",
71                        branchname => $branches->{$branch_hash}->{'branchname'},
72                        selected => ($branch_hash eq $branchcode?1:0)};
73 }
74
75 @branch_loop = sort {$a->{branchname} cmp $b->{branchname}} @branch_loop;
76 my @authorised_value_list;
77 my $authorisedvalue_categories = '';
78
79 my $frameworks = getframeworks();
80 $frameworks->{''} = {frameworkcode => ''}; # Add the default framework
81
82 for my $fwk (keys %$frameworks){
83   my $fwkcode = $frameworks->{$fwk}->{'frameworkcode'};
84   my $authcode = GetAuthValCode('items.location', $fwkcode);
85     if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
86       $authorisedvalue_categories.="$authcode ";
87       my $data=GetAuthorisedValues($authcode);
88       foreach my $value (@$data){
89         $value->{selected}=1 if ($value->{authorised_value} eq ($location));
90       }
91       push @authorised_value_list,@$data;
92     }
93 }
94
95 my $statuses = [];
96 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
97     my $hash = {};
98     $hash->{fieldname} = $statfield;
99     $hash->{authcode} = GetAuthValCode($statfield);
100     if ($hash->{authcode}){
101         my $arr = GetAuthorisedValues($hash->{authcode});
102         $hash->{values} = $arr;
103         push @$statuses, $hash;
104     }
105 }
106
107
108 $template->param( statuses => $statuses );
109 my $staton = {};                                #authorized values that are ticked
110 for my $authvfield (@$statuses) {
111     $staton->{$authvfield->{fieldname}} = [];
112     for my $authval (@{$authvfield->{values}}){
113         if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
114             push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
115         }
116     }
117 }
118
119 my $notforloanlist;
120 my $statussth = '';
121 for my $authvfield (@$statuses) {
122     if ( scalar @{$staton->{$authvfield->{fieldname}}} > 0 ){
123         my $joinedvals = join ',', @{$staton->{$authvfield->{fieldname}}};
124         $statussth .= "$authvfield->{fieldname} in ($joinedvals) and ";
125         $notforloanlist = $joinedvals if ($authvfield->{fieldname} eq "items.notforloan");
126     }
127 }
128 $statussth =~ s, and $,,g;
129 $template->param(
130     branchloop               => \@branch_loop,
131     authorised_values        => \@authorised_value_list,
132     today                    => dt_from_string,
133     minlocation              => $minlocation,
134     maxlocation              => $maxlocation,
135     location                 => $location,
136     ignoreissued             => $ignoreissued,
137     branchcode               => $branchcode,
138     branch                   => $branch,
139     datelastseen             => $datelastseen,
140     compareinv2barcd         => $compareinv2barcd,
141     notforloanlist           => $notforloanlist
142 );
143
144 my @notforloans;
145 if (defined $notforloanlist) {
146     @notforloans = split(/,/, $notforloanlist);
147 }
148
149 my @scanned_items;
150 my @errorloop;
151 if ( $uploadbarcodes && length($uploadbarcodes) > 0 ) {
152     my $dbh = C4::Context->dbh;
153     my $date = dt_from_string( $input->param('setdate') );
154     $date = output_pref( $date, 'iso' );
155
156     my $strsth  = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
157     my $qonloan = $dbh->prepare($strsth);
158     $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
159     my $qwithdrawn = $dbh->prepare($strsth);
160
161     my $count = 0;
162
163     while (my $barcode=<$uploadbarcodes>){
164         $barcode =~ s/\r?\n$//;
165         next unless $barcode;
166         if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
167             push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
168         } else {
169             my $item = GetItem( '', $barcode );
170             if ( defined $item && $item->{'itemnumber'} ) {
171                 ModItem( { datelastseen => $date }, undef, $item->{'itemnumber'} );
172                 push @scanned_items, $item;
173                 $count++;
174                 $qonloan->execute($barcode);
175                 if ($qonloan->rows){
176                     my $data = $qonloan->fetchrow_hashref;
177                     my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
178                     if ($doreturn){
179                         push @errorloop, {'barcode'=>$barcode,'ERR_ONLOAN_RET'=>1}
180                     } else {
181                         push @errorloop, {'barcode'=>$barcode,'ERR_ONLOAN_NOT_RET'=>1}
182                     }
183                 }
184             } else {
185                 push @errorloop, {'barcode'=>$barcode,'ERR_BARCODE'=>1};
186             }
187         }
188
189     }
190
191     $template->param( date => $date, Number => $count );
192     $template->param( errorloop => \@errorloop ) if (@errorloop);
193 }
194
195 # now build the result list: inventoried items if requested, and mis-placed items -always-
196 my $inventorylist;
197 my @items_with_problems;
198 if ( $markseen or $op ) {
199     # retrieve all items in this range.
200     my $totalrecords;
201     ($inventorylist, $totalrecords) = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype, $ignoreissued, '', $branchcode, $branch, 0, undef , $staton);
202 }
203
204 # If "compare barcodes list to results" has been checked, we want to alert for missing items
205 if ( $compareinv2barcd ) {
206     # set "missing" flags for all items with a datelastseen (dls) before the choosen datelastseen (cdls)
207     my $dls = output_pref( dt_from_string( $datelastseen ), 'iso' );
208     foreach my $item ( @$inventorylist ) {
209         my $cdls = output_pref( dt_from_string( $_->{datelastseen} ), 'iso' );
210         if ( $cdls lt $dls ) {
211             $item->{problem} = 'missingitem';
212             # We have to push a copy of the item, not the reference
213             push @items_with_problems, { %$item };
214         }
215     }
216 }
217
218
219
220 # insert "wrongplace" to all scanned items that are not supposed to be in this range
221 # note this list is always displayed, whatever the librarian has choosen for comparison
222 my $moddatecount = 0;
223 foreach my $item ( @scanned_items ) {
224
225   # Saving notforloan code before it's replaced by it's authorised value for later comparison
226   $item->{notforloancode} = $item->{notforloan};
227
228   # Populating with authorised values
229   foreach my $field ( keys %$item ) {
230         # If the koha field is mapped to a marc field
231         my $fc = $item->{'frameworkcode'} || '';
232         my ($f, $sf) = GetMarcFromKohaField("items.$field", $fc);
233         if ($f and $sf) {
234             # We replace the code with it's description
235             my $authvals = C4::Koha::GetKohaAuthorisedValuesFromField($f, $sf, $fc);
236             if ($authvals and defined $item->{$field} and defined $authvals->{$item->{$field}}) {
237               $item->{$field} = $authvals->{$item->{$field}};
238             }
239         }
240     }
241
242     next if $item->{onloan}; # skip checked out items
243
244     # If we have scanned items with a non-matching notforloan value
245     if (none { $item->{'notforloancode'} eq $_ } @notforloans) {
246         $item->{problem} = 'changestatus';
247         push @items_with_problems, { %$item };
248     }
249     if (none { $item->{barcode} eq $_->{barcode} && !$_->{'onloan'} } @$inventorylist) {
250         $item->{problem} = 'wrongplace';
251         push @items_with_problems, { %$item };
252     }
253
254     # Modify date last seen for scanned items
255     ModDateLastSeen($_->{'itemnumber'});
256     $moddatecount++;
257 }
258
259 if ( $compareinv2barcd ) {
260     my @scanned_barcodes = map {$_->{barcode}} @scanned_items;
261     for my $should_be_scanned ( @$inventorylist ) {
262         my $barcode = $should_be_scanned->{barcode};
263         unless ( grep /^$barcode$/, @scanned_barcodes ) {
264             $should_be_scanned->{problem} = 'not_scanned';
265             push @items_with_problems, { %$should_be_scanned };
266         }
267     }
268 }
269
270 for my $item ( @items_with_problems ) {
271     my $biblio = C4::Biblio::GetBiblioData($item->{biblionumber});
272     $item->{title} = $biblio->{title};
273     $item->{author} = $biblio->{author};
274 }
275
276 # If a barcode file is given, we want to show problems, else all items
277 my @results;
278 @results = $uploadbarcodes
279             ? @items_with_problems
280             : $op
281                 ? @$inventorylist
282                 : ();
283
284 $template->param(
285     moddatecount => $moddatecount,
286     loop       => \@results,
287     op         => $op
288 );
289
290 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
291     eval {use Text::CSV};
292     my $csv = Text::CSV->new or
293             die Text::CSV->error_diag ();
294     binmode STDOUT, ":encoding(UTF-8)";
295     print $input->header(
296         -type       => 'text/csv',
297         -attachment => 'inventory.csv',
298     );
299
300     my $columns_def_hashref = C4::Reports::Guided::_get_column_defs($input);
301     foreach my $key ( keys %$columns_def_hashref ) {
302         my $initkey = $key;
303         $key =~ s/[^\.]*\.//;
304         $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey} // '');
305         $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
306     }
307
308     my @translated_keys;
309     for my $key (qw / biblioitems.title    biblio.author
310                       items.barcode        items.itemnumber
311                       items.homebranch     items.location
312                       items.itemcallnumber items.notforloan
313                       items.itemlost       items.damaged
314                       items.stocknumber
315                       / ) {
316        push @translated_keys, $columns_def_hashref->{$key};
317     }
318     push @translated_keys, 'problem' if $uploadbarcodes;
319
320     $csv->combine(@translated_keys);
321     print $csv->string, "\n";
322
323     my @keys = qw / title author barcode itemnumber homebranch location itemcallnumber notforloan lost damaged stocknumber /;
324     for my $item ( @results ) {
325         my @line;
326         for my $key (@keys) {
327             push @line, $item->{$key};
328         }
329         if ( defined $item->{problem} ) {
330             if ( $item->{problem} eq 'wrongplace' ) {
331                 push @line, "wrong place";
332             } elsif ( $item->{problem} eq 'missingitem' ) {
333                 push @line, "missing item";
334             } elsif ( $item->{problem} eq 'changestatus' ) {
335                 push @line, "change item status";
336             } elsif ($item->{problem} eq 'not_scanned' ) {
337                 push @line, "item not scanned";
338             }
339         }
340         $csv->combine(@line);
341         print $csv->string, "\n";
342     }
343     # Adding not found barcodes
344     foreach my $error (@errorloop) {
345         my @line;
346         if ($error->{'ERR_BARCODE'}) {
347             push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
348             push @line, "barcode not found";
349             $csv->combine(@line);
350             print $csv->string, "\n";
351         }
352     }
353     exit;
354 }
355
356 output_html_with_http_headers $input, $cookie, $template->output;