Bug 7684: multiple fixes for inventory
[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::Dates qw/format_date format_date_in_iso/;
35 use C4::Koha;
36 use C4::Branch; # GetBranches
37 use C4::Circulation;
38 use C4::Reports::Guided;    #_get_column_defs
39 use C4::Charset;
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 $offset = $input->param('offset');
51 my $markseen = $input->param('markseen');
52 $offset=0 unless $offset;
53 my $pagesize = $input->param('pagesize');
54 $pagesize=50 unless $pagesize;
55 my $branchcode = $input->param('branchcode') || '';
56 my $branch     = $input->param('branch');
57 my $op         = $input->param('op');
58 my $compareinv2barcd = $input->param('compareinv2barcd');
59 my $res;                                            #contains the results loop
60
61 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
62     {   template_name   => "tools/inventory.tmpl",
63         query           => $input,
64         type            => "intranet",
65         authnotrequired => 0,
66         flagsrequired   => { tools => 'inventory' },
67         debug           => 1,
68     }
69 );
70
71
72 my $branches = GetBranches();
73 my @branch_loop;
74 for my $branch_hash (keys %$branches) {
75     push @branch_loop, {value => "$branch_hash",
76                        branchname => $branches->{$branch_hash}->{'branchname'},
77                        selected => ($branch_hash eq $branchcode?1:0)};
78 }
79
80 @branch_loop = sort {$a->{branchname} cmp $b->{branchname}} @branch_loop;
81 my @authorised_value_list;
82 my $authorisedvalue_categories = '';
83
84 my $frameworks = getframeworks();
85 $frameworks->{''} = {frameworkcode => ''}; # Add the default framework
86
87 for my $fwk (keys %$frameworks){
88   my $fwkcode = $frameworks->{$fwk}->{'frameworkcode'};
89   my $authcode = GetAuthValCode('items.location', $fwkcode);
90     if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){
91       $authorisedvalue_categories.="$authcode ";
92       my $data=GetAuthorisedValues($authcode);
93       foreach my $value (@$data){
94         $value->{selected}=1 if ($value->{authorised_value} eq ($location));
95       }
96       push @authorised_value_list,@$data;
97     }
98 }
99
100 my $statuses = [];
101 for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){
102     my $hash = {};
103     $hash->{fieldname} = $statfield;
104     $hash->{authcode} = GetAuthValCode($statfield);
105     if ($hash->{authcode}){
106         my $arr = GetAuthorisedValues($hash->{authcode});
107         $hash->{values} = $arr;
108         push @$statuses, $hash;
109     }
110 }
111
112
113 $template->param( statuses => $statuses );
114 my $staton = {};                                #authorized values that are ticked
115 for my $authvfield (@$statuses) {
116     $staton->{$authvfield->{fieldname}} = [];
117     for my $authval (@{$authvfield->{values}}){
118         if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){
119             push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value};
120         }
121     }
122 }
123
124 my $notforloanlist;
125 my $statussth = '';
126 for my $authvfield (@$statuses) {
127     if ( scalar @{$staton->{$authvfield->{fieldname}}} > 0 ){
128         my $joinedvals = join ',', @{$staton->{$authvfield->{fieldname}}};
129         $statussth .= "$authvfield->{fieldname} in ($joinedvals) and ";
130         $notforloanlist = $joinedvals if ($authvfield->{fieldname} eq "items.notforloan");
131     }
132 }
133 $statussth =~ s, and $,,g;
134 $template->param(
135     branchloop               => \@branch_loop,
136     authorised_values        => \@authorised_value_list,
137     today                    => C4::Dates->today(),
138     minlocation              => $minlocation,
139     maxlocation              => $maxlocation,
140     location                 => $location,
141     ignoreissued             => $ignoreissued,
142     branchcode               => $branchcode,
143     branch                   => $branch,
144     offset                   => $offset,
145     pagesize                 => $pagesize,
146     datelastseen             => $datelastseen,
147     compareinv2barcd         => $compareinv2barcd,
148     notforloanlist           => $notforloanlist
149 );
150
151 my @notforloans;
152 if (defined $notforloanlist) {
153     @notforloans = split(/,/, $notforloanlist);
154 }
155
156
157
158 my @brcditems;
159 my $barcodelist;
160 my @errorloop;
161 if ( $uploadbarcodes && length($uploadbarcodes) > 0 ) {
162     my $dbh = C4::Context->dbh;
163     my $date = format_date_in_iso( $input->param('setdate') ) || C4::Dates->today('iso');
164
165     my $strsth  = "select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =?";
166     my $qonloan = $dbh->prepare($strsth);
167     $strsth="select * from items where items.barcode =? and items.withdrawn = 1";
168     my $qwithdrawn = $dbh->prepare($strsth);
169
170     my $count = 0;
171
172     while (my $barcode=<$uploadbarcodes>){
173         $barcode =~ s/\r?\n$//;
174         $barcodelist .= ($barcodelist) ? '|' . $barcode : $barcode;
175         if ( $qwithdrawn->execute($barcode) && $qwithdrawn->rows ) {
176             push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 };
177         } else {
178             my $item = GetItem( '', $barcode );
179             if ( defined $item && $item->{'itemnumber'} ) {
180                 ModItem( { datelastseen => $date }, undef, $item->{'itemnumber'} );
181                 push @brcditems, $item;
182                 $count++;
183                 $qonloan->execute($barcode);
184                 if ($qonloan->rows){
185                     my $data = $qonloan->fetchrow_hashref;
186                     my ($doreturn, $messages, $iteminformation, $borrower) =AddReturn($barcode, $data->{homebranch});
187                     if ($doreturn){
188                         push @errorloop, {'barcode'=>$barcode,'ERR_ONLOAN_RET'=>1}
189                     } else {
190                         push @errorloop, {'barcode'=>$barcode,'ERR_ONLOAN_NOT_RET'=>1}
191                     }
192                 }
193             } else {
194                 push @errorloop, {'barcode'=>$barcode,'ERR_BARCODE'=>1};
195             }
196         }
197
198     }
199     $qonloan->finish;
200     $qwithdrawn->finish;
201     $template->param( date => format_date($date), Number => $count );
202     $template->param( errorloop => \@errorloop ) if (@errorloop);
203
204 }
205 $template->param(barcodelist => $barcodelist);
206
207 # now build the result list: inventoried items if requested, and mis-placed items -always-
208 my $inventorylist;
209 if ( $markseen or $op ) {
210     # retrieve all items in this range.
211     my $totalrecords;
212     ($inventorylist, $totalrecords) = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype, $ignoreissued, '', $branchcode, $branch, 0, undef , $staton);
213
214     # Real copy
215     my @res_copy;
216     foreach (@$inventorylist) {
217         push @res_copy, $_;
218     }
219     $res = \@res_copy;
220 }
221
222 # set "missing" flags for all items with a datelastseen before the choosen datelastseen
223 foreach (@$res) { $_->{missingitem}=1 if C4::Dates->new($_->{datelastseen})->output('iso') lt C4::Dates->new($datelastseen)->output('iso'); }
224
225 # removing missing items from loop if "Compare barcodes list to results" has not been checked
226 @$res = grep {!$_->{missingitem} == 1 } @$res if (!$input->param('compareinv2barcd'));
227
228 # insert "wrongplace" to all scanned items that are not supposed to be in this range
229 # note this list is always displayed, whatever the librarian has choosen for comparison
230 foreach my $temp (@brcditems) {
231
232   # Saving notforloan code before it's replaced by it's authorised value for later comparison
233   $temp->{'notforloancode'} = $temp->{'notforloan'};
234
235   # Populating with authorised values
236   foreach (keys %$temp) {
237         # If the koha field is mapped to a marc field
238         my $fc = $temp->{'frameworkcode'} || '';
239         my ($f, $sf) = GetMarcFromKohaField("items.$_", $fc);
240         if ($f and $sf) {
241             # We replace the code with it's description
242             my $authvals = C4::Koha::GetKohaAuthorisedValuesFromField($f, $sf, $fc);
243             if ($authvals and defined $temp->{$_} and defined $authvals->{$temp->{$_}}) {
244               $temp->{$_} = $authvals->{$temp->{$_}};
245             }
246         }
247     }
248
249     next if $temp->{onloan}; # skip checked out items
250
251     # If we have scanned items with a non-matching notforloan value
252     if (none { $temp->{'notforloancode'} eq $_ } @notforloans) {
253         $temp->{'changestatus'} = 1;
254         my $biblio = C4::Biblio::GetBiblioData($temp->{biblionumber});
255         $temp->{title} = $biblio->{title};
256         $temp->{author} = $biblio->{author};
257         $temp->{datelastseen} = format_date($temp->{datelastseen});
258         push @$res, $temp;
259
260     }
261     if (none { $temp->{barcode} eq $_->{barcode} && !$_->{'onloan'} } @$inventorylist) {
262         my $temp2 = { %$temp };
263         $temp2->{wrongplace}=1;
264         my $biblio = C4::Biblio::GetBiblioData($temp->{biblionumber});
265         $temp2->{title} = $biblio->{title};
266         $temp2->{author} = $biblio->{author};
267         $temp2->{datelastseen} = format_date($temp->{datelastseen});
268         push @$res, $temp2;
269     }
270 }
271
272 # Finally, modifying datelastseen for remaining items
273 my $moddatecount = 0;
274 foreach (@$res) {
275     unless ($_->{'missingitem'}) {
276         ModDateLastSeen($_->{'itemnumber'});
277         $moddatecount++;
278     }
279 }
280
281 # Removing items that don't have any problems from loop
282 @$res = grep { $_->{missingitem} || $_->{wrongplace} || $_->{changestatus} } @$res;
283
284 $template->param(
285     moddatecount => $moddatecount,
286     loop       => $res,
287     nextoffset => ( $offset + $pagesize ),
288     prevoffset => ( $offset ? $offset - $pagesize : 0 ),
289     op         => $op
290 );
291
292 if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){
293     eval {use Text::CSV};
294     my $csv = Text::CSV->new or
295             die Text::CSV->error_diag ();
296     print $input->header(
297         -type       => 'text/csv',
298         -attachment => 'inventory.csv',
299     );
300
301     my $columns_def_hashref = C4::Reports::Guided::_get_column_defs();
302     foreach my $key ( keys %$columns_def_hashref ) {
303         my $initkey = $key;
304         $key =~ s/[^\.]*\.//;
305         $columns_def_hashref->{$initkey}=NormalizeString($columns_def_hashref->{$initkey});
306         $columns_def_hashref->{$key} = $columns_def_hashref->{$initkey};
307     }
308
309     my @translated_keys;
310     for my $key (qw / biblioitems.title    biblio.author
311                       items.barcode        items.itemnumber
312                       items.homebranch     items.location
313                       items.itemcallnumber items.notforloan
314                       items.itemlost       items.damaged
315                       items.stocknumber
316                       / ) {
317        push @translated_keys, $columns_def_hashref->{$key};
318     }
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 $re (@$res) {
325         my @line;
326         for my $key (@keys) {
327             push @line, $re->{$key};
328         }
329         if ($re->{wrongplace}) {
330             push @line, "wrong place";
331         } elsif ($re->{missingitem}) {
332             push @line, "missing item";
333         } elsif ($re->{changestatus}) {
334             push @line, "change item status";
335         }
336         $csv->combine(@line);
337         print $csv->string, "\n";
338     }
339     # Adding not found barcodes
340     foreach my $error (@errorloop) {
341     my @line;
342     if ($error->{'ERR_BARCODE'}) {
343         push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys;
344         push @line, "barcode not found";
345         $csv->combine(@line);
346         print $csv->string, "\n";
347     }
348     }
349     exit;
350 }
351
352 output_html_with_http_headers $input, $cookie, $template->output;