Bug 12913 - wrong inventory results when notforloan filter is not used
[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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
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 qw ( -utf8 );
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::Circulation;
36 use C4::Reports::Guided;    #_get_column_defs
37 use C4::Charset;
38 use Koha::DateUtils;
39 use Koha::AuthorisedValues;
40 use Koha::BiblioFrameworks;
41 use List::MoreUtils qw( none );
42
43
44 my $minlocation=$input->param('minlocation') || '';
45 my $maxlocation=$input->param('maxlocation');
46 $maxlocation=$minlocation.'Z' unless ( $maxlocation || ! $minlocation );
47 my $location=$input->param('location') || '';
48 my $itemtype=$input->param('itemtype'); # FIXME note, template does not currently supply this
49 my $ignoreissued=$input->param('ignoreissued');
50 my $datelastseen = $input->param('datelastseen');
51 my $markseen = $input->param('markseen');
52 my $branchcode = $input->param('branchcode') || '';
53 my $branch     = $input->param('branch');
54 my $op         = $input->param('op');
55 my $compareinv2barcd = $input->param('compareinv2barcd');
56 my $dont_checkin = $input->param('dont_checkin');
57
58 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
59     {   template_name   => "tools/inventory.tt",
60         query           => $input,
61         type            => "intranet",
62         authnotrequired => 0,
63         flagsrequired   => { tools => 'inventory' },
64         debug           => 1,
65     }
66 );
67
68 my @authorised_value_list;
69 my $authorisedvalue_categories = '';
70
71 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed;
72 unshift @$frameworks, { frameworkcode => '' };
73
74 for my $fwk ( @$frameworks ){
75   my $fwkcode = $fwk->{frameworkcode};
76   my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fwkcode, kohafield => 'items.location', authorised_value => { not => undef } });
77   my $authcode = $mss->count ? $mss->next->authorised_value : undef;
78     if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
79       $authorisedvalue_categories.="$authcode ";
80       my $data=GetAuthorisedValues($authcode);
81       foreach my $value (@$data){
82         $value->{selected}=1 if ($value->{authorised_value} eq ($location));
83       }
84       push @authorised_value_list,@$data;
85     }
86 }
87
88 my $statuses = [];
89 my @notforloans;
90 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
91     my $hash = {};
92     $hash->{fieldname} = $statfield;
93     my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => $statfield, authorised_value => { not => undef } });
94     $hash->{authcode} = $mss->count ? $mss->next->authorised_value : undef;
95     if ($hash->{authcode}){
96         my $arr = GetAuthorisedValues($hash->{authcode});
97         $hash->{values} = $arr;
98         push @$statuses, $hash;
99         if ( $statfield eq 'items.notforloan') {
100             @notforloans = map { $_->{'authorised_value'} } @$arr;
101         }
102     }
103 }
104
105
106 $template->param( statuses => $statuses );
107 my $staton = {};                                #authorized values that are ticked
108 for my $authvfield (@$statuses) {
109     $staton->{$authvfield->{fieldname}} = [];
110     for my $authval (@{$authvfield->{values}}){
111         if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
112             push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
113         }
114     }
115 }
116
117 $template->param(
118     authorised_values        => \@authorised_value_list,
119     today                    => dt_from_string,
120     minlocation              => $minlocation,
121     maxlocation              => $maxlocation,
122     location                 => $location,
123     ignoreissued             => $ignoreissued,
124     branchcode               => $branchcode,
125     branch                   => $branch,
126     datelastseen             => $datelastseen,
127     compareinv2barcd         => $compareinv2barcd,
128 );
129
130 my @scanned_items;
131 my @errorloop;
132 if ( $uploadbarcodes && length($uploadbarcodes) > 0 ) {
133     my $dbh = C4::Context->dbh;
134     my $date = dt_from_string( scalar $input->param('setdate') );
135     $date = output_pref ( { dt => $date, dateformat => 'iso' } );
136
137     my $strsth  = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
138     my $qonloan = $dbh->prepare($strsth);
139     $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
140     my $qwithdrawn = $dbh->prepare($strsth);
141
142     my $count = 0;
143
144     my @barcodes;
145     my @uploadedbarcodes;
146
147     my $sth = $dbh->column_info(undef,undef,"items","barcode");
148     my $barcode_def = $sth->fetchall_hashref('COLUMN_NAME');
149     my $barcode_size = $barcode_def->{barcode}->{COLUMN_SIZE};
150     my $err_length=0;
151     my $err_data=0;
152     my $lines_read=0;
153     binmode($uploadbarcodes, ":encoding(UTF-8)");
154     while (my $barcode=<$uploadbarcodes>) {
155         $barcode =~ s/\r/\n/g;
156         $barcode =~ s/\n\n/\n/g;
157         my @data = split(/\n/,$barcode);
158         push @uploadedbarcodes, @data;
159     }
160     for my $barcode (@uploadedbarcodes) {
161         next unless $barcode;
162         ++$lines_read;
163         if (length($barcode)>$barcode_size) {
164             $err_length += 1;
165         }
166         my $check_barcode = $barcode;
167         $check_barcode =~ s/\p{Print}//g;
168         if (length($check_barcode)>0) { # Only printable unicode characters allowed.
169             $err_data += 1;
170         }
171         next if length($barcode)>$barcode_size;
172         next if ( length($check_barcode)>0 );
173         push @barcodes,$barcode;
174     }
175     $template->param( LinesRead => $lines_read );
176     if (! @barcodes) {
177         push @errorloop, {'barcode'=>'No valid barcodes!'};
178         $op=''; # force the initial inventory screen again.
179     }
180     else {
181         $template->param( err_length => $err_length,
182                           err_data   => $err_data );
183     }
184     foreach my $barcode (@barcodes) {
185         if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
186             push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
187         } else {
188             my $item = GetItem( '', $barcode );
189             if ( defined $item && $item->{'itemnumber'} ) {
190                 ModItem( { datelastseen => $date }, undef, $item->{'itemnumber'} );
191                 push @scanned_items, $item;
192                 $count++;
193                 unless ( $dont_checkin ) {
194                     $qonloan->execute($barcode);
195                     if ($qonloan->rows){
196                         my $data = $qonloan->fetchrow_hashref;
197                         my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
198                         if ($doreturn){
199                             push @errorloop, {'barcode'=>$barcode,'ERR_ONLOAN_RET'=>1}
200                         } else {
201                             push @errorloop, {'barcode'=>$barcode,'ERR_ONLOAN_NOT_RET'=>1}
202                         }
203                     }
204                 }
205             } else {
206                 push @errorloop, {'barcode'=>$barcode,'ERR_BARCODE'=>1};
207             }
208         }
209
210     }
211
212     $template->param( date => $date, Number => $count );
213     $template->param( errorloop => \@errorloop ) if (@errorloop);
214 }
215
216 # now build the result list: inventoried items if requested, and mis-placed items -always-
217 my $inventorylist;
218 my $wrongplacelist;
219 my @items_with_problems;
220 if ( $markseen or $op ) {
221     # retrieve all items in this range.
222     my $totalrecords;
223
224     # We use datelastseen only when comparing the results to the barcode file.
225     my $paramdatelastseen = ($compareinv2barcd) ? $datelastseen : '';
226     ($inventorylist, $totalrecords) = GetItemsForInventory( {
227       minlocation  => $minlocation,
228       maxlocation  => $maxlocation,
229       location     => $location,
230       itemtype     => $itemtype,
231       ignoreissued => $ignoreissued,
232       datelastseen => $paramdatelastseen,
233       branchcode   => $branchcode,
234       branch       => $branch,
235       offset       => 0,
236       size         => undef,
237       statushash   => $staton,
238     } );
239
240     # For the items that may be marked as "wrong place", we only check the location (callnumbers, location and branch)
241     ($wrongplacelist, $totalrecords) = GetItemsForInventory( {
242       minlocation  => $minlocation,
243       maxlocation  => $maxlocation,
244       location     => $location,
245       itemtype     => undef,
246       ignoreissued => undef,
247       datelastseen => undef,
248       branchcode   => $branchcode,
249       branch       => $branch,
250       offset       => 0,
251       size         => undef,
252       statushash   => undef,
253     } );
254
255 }
256
257 # If "compare barcodes list to results" has been checked, we want to alert for missing items
258 if ( $compareinv2barcd ) {
259     # set "missing" flags for all items with a datelastseen (dls) before the chosen datelastseen (cdls)
260     my $dls = output_pref( { dt => dt_from_string( $datelastseen ),
261                              dateformat => 'iso' } );
262     foreach my $item ( @$inventorylist ) {
263         my $cdls = output_pref( { dt => dt_from_string( $item->{datelastseen} ),
264                                   dateformat => 'iso' } );
265         if ( $cdls lt $dls ) {
266             $item->{problem} = 'missingitem';
267             # We have to push a copy of the item, not the reference
268             push @items_with_problems, { %$item };
269         }
270     }
271 }
272
273
274
275 # insert "wrongplace" to all scanned items that are not supposed to be in this range
276 # note this list is always displayed, whatever the librarian has chosen for comparison
277 my $moddatecount = 0;
278 foreach my $item ( @scanned_items ) {
279
280   # Saving notforloan code before it's replaced by it's authorised value for later comparison
281   $item->{notforloancode} = $item->{notforloan};
282
283   # Populating with authorised values
284   foreach my $field ( keys %$item ) {
285         # If the koha field is mapped to a marc field
286         my $fc = $item->{'frameworkcode'} || '';
287         my ($f, $sf) = GetMarcFromKohaField("items.$field", $fc);
288         if ($f and $sf) {
289             # We replace the code with it's description
290             my $av = Koha::AuthorisedValues->search_by_marc_field({ frameworkcode => $fc, tagfield => $f, tagsubfield => $sf, });
291             $av = $av->count ? $av->unblessed : [];
292             my $authvals = { map { ( $_->{authorised_value} => $_->{lib} ) } @$av };
293             if ($authvals and defined $item->{$field} and defined $authvals->{$item->{$field}}) {
294               $item->{$field} = $authvals->{$item->{$field}};
295             }
296         }
297     }
298
299     next if $item->{onloan}; # skip checked out items
300
301     # If we have scanned items with a non-matching notforloan value
302     if (none { $item->{'notforloancode'} eq $_ } @notforloans) {
303         $item->{problem} = 'changestatus';
304         push @items_with_problems, { %$item };
305     }
306     if (none { $item->{barcode} eq $_->{barcode} && !$_->{'onloan'} } @$wrongplacelist) {
307         $item->{problem} = 'wrongplace';
308         push @items_with_problems, { %$item };
309     }
310
311     # Modify date last seen for scanned items
312     ModDateLastSeen($item->{'itemnumber'});
313     $moddatecount++;
314 }
315
316 if ( $compareinv2barcd ) {
317     my @scanned_barcodes = map {$_->{barcode}} @scanned_items;
318     for my $should_be_scanned ( @$inventorylist ) {
319         my $barcode = $should_be_scanned->{barcode};
320         unless ( grep /^$barcode$/, @scanned_barcodes ) {
321             $should_be_scanned->{problem} = 'not_scanned';
322             push @items_with_problems, { %$should_be_scanned };
323         }
324     }
325 }
326
327 for my $item ( @items_with_problems ) {
328     my $biblio = C4::Biblio::GetBiblioData($item->{biblionumber});
329     $item->{title} = $biblio->{title};
330     $item->{author} = $biblio->{author};
331 }
332
333 # If a barcode file is given, we want to show problems, else all items
334 my @results;
335 @results = $uploadbarcodes
336             ? @items_with_problems
337             : $op
338                 ? @$inventorylist
339                 : ();
340
341 $template->param(
342     moddatecount => $moddatecount,
343     loop       => \@results,
344     op         => $op
345 );
346
347 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
348     eval {use Text::CSV};
349     my $csv = Text::CSV->new or
350             die Text::CSV->error_diag ();
351     binmode STDOUT, ":encoding(UTF-8)";
352     print $input->header(
353         -type       => 'text/csv',
354         -attachment => 'inventory.csv',
355     );
356
357     my $columns_def_hashref = C4::Reports::Guided::_get_column_defs($input);
358     foreach my $key ( keys %$columns_def_hashref ) {
359         my $initkey = $key;
360         $key =~ s/[^\.]*\.//;
361         $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey} // '');
362         $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
363     }
364
365     my @translated_keys;
366     for my $key (qw / biblioitems.title    biblio.author
367                       items.barcode        items.itemnumber
368                       items.homebranch     items.location
369                       items.itemcallnumber items.notforloan
370                       items.itemlost       items.damaged
371                       items.withdrawn      items.stocknumber
372                       / ) {
373        push @translated_keys, $columns_def_hashref->{$key};
374     }
375     push @translated_keys, 'problem' if $uploadbarcodes;
376
377     $csv->combine(@translated_keys);
378     print $csv->string, "\n";
379
380     my @keys = qw / title author barcode itemnumber homebranch location itemcallnumber notforloan lost damaged withdrawn stocknumber /;
381     for my $item ( @results ) {
382         my @line;
383         for my $key (@keys) {
384             push @line, $item->{$key};
385         }
386         if ( defined $item->{problem} ) {
387             if ( $item->{problem} eq 'wrongplace' ) {
388                 push @line, "wrong place";
389             } elsif ( $item->{problem} eq 'missingitem' ) {
390                 push @line, "missing item";
391             } elsif ( $item->{problem} eq 'changestatus' ) {
392                 push @line, "change item status";
393             } elsif ($item->{problem} eq 'not_scanned' ) {
394                 push @line, "item not scanned";
395             }
396         }
397         $csv->combine(@line);
398         print $csv->string, "\n";
399     }
400     # Adding not found barcodes
401     foreach my $error (@errorloop) {
402         my @line;
403         if ($error->{'ERR_BARCODE'}) {
404             push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
405             push @line, "barcode not found";
406             $csv->combine(@line);
407             print $csv->string, "\n";
408         }
409     }
410     exit;
411 }
412
413 output_html_with_http_headers $input, $cookie, $template->output;