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