Bug 18539: remove occurrence in ReNewSubscription.t
[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 Modern::Perl;
22
23 #need to open cgi and get the fh before anything else opens a new cgi context (see C4::Auth)
24 use CGI qw ( -utf8 );
25 my $input = CGI->new;
26 my $uploadbarcodes = $input->param('uploadbarcodes');
27
28 use C4::Auth;
29 use C4::Context;
30 use C4::Output;
31 use C4::Biblio;
32 use C4::Items;
33 use C4::Koha;
34 use C4::Circulation;
35 use C4::Reports::Guided;    #_get_column_defs
36 use C4::Charset;
37 use Koha::DateUtils;
38 use Koha::AuthorisedValues;
39 use Koha::BiblioFrameworks;
40 use List::MoreUtils qw( none );
41
42 my $minlocation=$input->param('minlocation') || '';
43 my $maxlocation=$input->param('maxlocation');
44 $maxlocation=$minlocation.'Z' unless ( $maxlocation || ! $minlocation );
45 my $location=$input->param('location') || '';
46 my $ignoreissued=$input->param('ignoreissued');
47 my $datelastseen = $input->param('datelastseen'); # last inventory date
48 my $branchcode = $input->param('branchcode') || '';
49 my $branch     = $input->param('branch');
50 my $op         = $input->param('op');
51 my $compareinv2barcd = $input->param('compareinv2barcd');
52 my $dont_checkin = $input->param('dont_checkin');
53
54 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
55     {   template_name   => "tools/inventory.tt",
56         query           => $input,
57         type            => "intranet",
58         authnotrequired => 0,
59         flagsrequired   => { tools => 'inventory' },
60         debug           => 1,
61     }
62 );
63
64 my @authorised_value_list;
65 my $authorisedvalue_categories = '';
66
67 my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed;
68 unshift @$frameworks, { frameworkcode => '' };
69
70 for my $fwk ( @$frameworks ){
71   my $fwkcode = $fwk->{frameworkcode};
72   my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fwkcode, kohafield => 'items.location', authorised_value => { not => undef } });
73   my $authcode = $mss->count ? $mss->next->authorised_value : undef;
74     if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
75       $authorisedvalue_categories.="$authcode ";
76       my $data=GetAuthorisedValues($authcode);
77       foreach my $value (@$data){
78         $value->{selected}=1 if ($value->{authorised_value} eq ($location));
79       }
80       push @authorised_value_list,@$data;
81     }
82 }
83
84 my $statuses = [];
85 my @notforloans;
86 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
87     my $hash = {};
88     $hash->{fieldname} = $statfield;
89     my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => $statfield, authorised_value => { not => undef } });
90     $hash->{authcode} = $mss->count ? $mss->next->authorised_value : undef;
91     if ($hash->{authcode}){
92         my $arr = GetAuthorisedValues($hash->{authcode});
93         if ( $statfield eq 'items.notforloan') {
94             # Add notforloan == 0 to the list of possible notforloan statuses
95             # The lib value is replaced in the template
96             push @$arr, { authorised_value => 0, id => 'stat0' , lib => 'ignore' } if ! grep { $_->{authorised_value} eq '0' } @$arr;
97             @notforloans = map { $_->{'authorised_value'} } @$arr;
98         }
99         $hash->{values} = $arr;
100         push @$statuses, $hash;
101     }
102 }
103
104 $template->param( statuses => $statuses );
105 my $staton = {}; #authorized values that are ticked
106 for my $authvfield (@$statuses) {
107     $staton->{$authvfield->{fieldname}} = [];
108     for my $authval (@{$authvfield->{values}}){
109         if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
110             push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
111         }
112     }
113 }
114
115 $template->param(
116     authorised_values        => \@authorised_value_list,
117     today                    => dt_from_string,
118     minlocation              => $minlocation,
119     maxlocation              => $maxlocation,
120     location                 => $location,
121     ignoreissued             => $ignoreissued,
122     branchcode               => $branchcode,
123     branch                   => $branch,
124     datelastseen             => $datelastseen,
125     compareinv2barcd         => $compareinv2barcd,
126     uploadedbarcodesflag     => $uploadbarcodes ? 1 : 0,
127 );
128
129 # Walk through uploaded barcodes, report errors, mark as seen, check in
130 my $results = {};
131 my @scanned_items;
132 my @errorloop;
133 my $moddatecount = 0;
134 if ( $uploadbarcodes && length($uploadbarcodes) > 0 ) {
135     my $dbh = C4::Context->dbh;
136     my $date = dt_from_string( scalar $input->param('setdate') );
137     $date = output_pref ( { dt => $date, dateformat => 'iso' } );
138
139     my $strsth  = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
140     my $qonloan = $dbh->prepare($strsth);
141     $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
142     my $qwithdrawn = $dbh->prepare($strsth);
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                 # Modify date last seen for scanned items, remove lost status
191                 ModItem( { itemlost => 0, datelastseen => $date }, undef, $item->{'itemnumber'} );
192                 $moddatecount++;
193                 # update item hash accordingly
194                 $item->{itemlost} = 0;
195                 $item->{datelastseen} = $date;
196                 unless ( $dont_checkin ) {
197                     $qonloan->execute($barcode);
198                     if ($qonloan->rows){
199                         my $data = $qonloan->fetchrow_hashref;
200                         my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
201                         if( $doreturn ) {
202                             $item->{onloan} = undef;
203                             $item->{datelastseen} = dt_from_string;
204                         } else {
205                             push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 };
206                         }
207                     }
208                 }
209                 push @scanned_items, $item;
210             } else {
211                 push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 };
212             }
213         }
214     }
215     $template->param( date => $date );
216     $template->param( errorloop => \@errorloop ) if (@errorloop);
217 }
218
219 # Build inventorylist: used as result list when you do not pass barcodes
220 # This list is also used when you want to compare with barcodes
221 my ( $inventorylist, $rightplacelist );
222 if ( $op && ( !$uploadbarcodes || $compareinv2barcd )) {
223     ( $inventorylist ) = GetItemsForInventory({
224       minlocation  => $minlocation,
225       maxlocation  => $maxlocation,
226       location     => $location,
227       ignoreissued => $ignoreissued,
228       datelastseen => $datelastseen,
229       branchcode   => $branchcode,
230       branch       => $branch,
231       offset       => 0,
232       statushash   => $staton,
233     });
234 }
235 # Build rightplacelist used to check if a scanned item is in the right place.
236 if( @scanned_items ) {
237     ( $rightplacelist ) = GetItemsForInventory({
238       minlocation  => $minlocation,
239       maxlocation  => $maxlocation,
240       location     => $location,
241       ignoreissued => undef,
242       datelastseen => undef,
243       branchcode   => $branchcode,
244       branch       => $branch,
245       offset       => 0,
246       statushash   => undef,
247     });
248     # Convert the structure to a hash on barcode
249     $rightplacelist = {
250         map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist
251     };
252 }
253
254 # Report scanned items that are on the wrong place, or have a wrong notforloan
255 # status, or are still checked out.
256 foreach my $item ( @scanned_items ) {
257     $item->{notforloancode} = $item->{notforloan}; # save for later use
258
259     # Populating with authorised values
260     foreach my $field ( keys %$item ) {
261         # If the koha field is mapped to a marc field
262         my $fc = $item->{'frameworkcode'} || '';
263         my ($f, $sf) = GetMarcFromKohaField("items.$field", $fc);
264         if ($f and $sf) {
265             # We replace the code with it's description
266             my $av = Koha::AuthorisedValues->search_by_marc_field({ frameworkcode => $fc, tagfield => $f, tagsubfield => $sf, });
267             $av = $av->count ? $av->unblessed : [];
268             my $authvals = { map { ( $_->{authorised_value} => $_->{lib} ) } @$av };
269             if ($authvals and defined $item->{$field} and defined $authvals->{$item->{$field}}) {
270               $item->{$field} = $authvals->{$item->{$field}};
271             }
272         }
273     }
274
275     # If we have scanned items with a non-matching notforloan value
276     if( none { $item->{'notforloancode'} eq $_ } @notforloans ) {
277         $item->{problems}->{changestatus} = 1;
278         additemtoresults( $item, $results );
279     }
280
281     # Report an item that is checked out (unusual!) or wrongly placed
282     if( $item->{onloan} ) {
283         $item->{problems}->{checkedout} = 1;
284         additemtoresults( $item, $results );
285         next; # do not modify item
286     } elsif( !exists $rightplacelist->{ $item->{barcode} } ) {
287         $item->{problems}->{wrongplace} = 1;
288         additemtoresults( $item, $results );
289     }
290 }
291
292 # Compare barcodes with inventory list, report no_barcode and not_scanned.
293 # not_scanned can be interpreted as missing
294 if ( $compareinv2barcd ) {
295     my @scanned_barcodes = map {$_->{barcode}} @scanned_items;
296     for my $item ( @$inventorylist ) {
297         my $barcode = $item->{barcode};
298         if( !$barcode ) {
299             $item->{problems}->{no_barcode} = 1;
300         } elsif ( grep /^$barcode$/, @scanned_barcodes ) {
301             next;
302         } else {
303             $item->{problems}->{not_scanned} = 1;
304         }
305         additemtoresults( $item, $results );
306     }
307 }
308
309 # Construct final results, add biblio information
310 my $loop = $uploadbarcodes
311     ? [ map { $results->{$_} } keys %$results ]
312     : $inventorylist // [];
313 for my $item ( @$loop ) {
314     my $biblio = C4::Biblio::GetBiblioData($item->{biblionumber});
315     $item->{title} = $biblio->{title};
316     $item->{author} = $biblio->{author};
317 }
318
319 $template->param(
320     moddatecount => $moddatecount,
321     loop         => $loop,
322     op           => $op,
323 );
324
325 # Export to csv
326 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
327     eval {use Text::CSV};
328     my $csv = Text::CSV->new or
329             die Text::CSV->error_diag ();
330     binmode STDOUT, ":encoding(UTF-8)";
331     print $input->header(
332         -type       => 'text/csv',
333         -attachment => 'inventory.csv',
334     );
335
336     my $columns_def_hashref = C4::Reports::Guided::_get_column_defs($input);
337     foreach my $key ( keys %$columns_def_hashref ) {
338         my $initkey = $key;
339         $key =~ s/[^\.]*\.//;
340         $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey} // '');
341         $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
342     }
343
344     my @translated_keys;
345     for my $key (qw / biblioitems.title    biblio.author
346                       items.barcode        items.itemnumber
347                       items.homebranch     items.location
348                       items.itemcallnumber items.notforloan
349                       items.itemlost       items.damaged
350                       items.withdrawn      items.stocknumber
351                       / ) {
352        push @translated_keys, $columns_def_hashref->{$key};
353     }
354     push @translated_keys, 'problem' if $uploadbarcodes;
355
356     $csv->combine(@translated_keys);
357     print $csv->string, "\n";
358
359     my @keys = qw / title author barcode itemnumber homebranch location itemcallnumber notforloan lost damaged withdrawn stocknumber /;
360     for my $item ( @$loop ) {
361         my @line;
362         for my $key (@keys) {
363             push @line, $item->{$key};
364         }
365         my $errstr = '';
366         foreach my $key ( keys %{$item->{problems}} ) {
367             if( $key eq 'wrongplace' ) {
368                 $errstr .= "wrong place,";
369             } elsif( $key eq 'changestatus' ) {
370                 $errstr .= "unknown notforloan status,";
371             } elsif( $key eq 'not_scanned' ) {
372                 $errstr .= "missing,";
373             } elsif( $key eq 'no_barcode' ) {
374                 $errstr .= "no barcode,";
375             } elsif( $key eq 'checkedout' ) {
376                 $errstr .= "checked out,";
377             }
378         }
379         $errstr =~ s/,$//;
380         push @line, $errstr;
381         $csv->combine(@line);
382         print $csv->string, "\n";
383     }
384     # Adding not found barcodes
385     foreach my $error (@errorloop) {
386         my @line;
387         if ($error->{'ERR_BARCODE'}) {
388             push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
389             push @line, "barcode not found";
390             $csv->combine(@line);
391             print $csv->string, "\n";
392         }
393     }
394     exit;
395 }
396
397 output_html_with_http_headers $input, $cookie, $template->output;
398
399 sub additemtoresults {
400     my ( $item, $results ) = @_;
401     my $itemno = $item->{itemnumber};
402     # since the script appends to $item, we can just overwrite the hash entry
403     $results->{$itemno} = $item;
404 }