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