User can upload a file with barcodes or with itemnumbers
[koha.git] / tools / batchMod.pl
1 #!/usr/bin/perl
2
3
4 # Copyright 2000-2002 Katipo Communications
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 with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 use CGI;
22 use strict;
23 use C4::Auth;
24 use C4::Output;
25 use C4::Biblio;
26 use C4::Items;
27 use C4::Context;
28 use C4::Koha; # XXX subfield_is_koha_internal_p
29 use C4::Branch; # XXX subfield_is_koha_internal_p
30 use C4::ClassSource;
31 use C4::Dates;
32 use C4::Debug;
33 use YAML;
34 use Switch;
35 use MARC::File::XML;
36
37 sub find_value {
38     my ($tagfield,$insubfield,$record) = @_;
39     my $result;
40     my $indicator;
41     foreach my $field ($record->field($tagfield)) {
42         my @subfields = $field->subfields();
43         foreach my $subfield (@subfields) {
44             if (@$subfield[0] eq $insubfield) {
45                 $result .= @$subfield[1];
46                 $indicator = $field->indicator(1).$field->indicator(2);
47             }
48         }
49     }
50     return($indicator,$result);
51 }
52
53
54 my $input = new CGI;
55 my $dbh = C4::Context->dbh;
56 my $error        = $input->param('error');
57 my @itemnumbers  = $input->param('itemnumber');
58 my $op           = $input->param('op');
59
60 my ($template, $loggedinuser, $cookie)
61     = get_template_and_user({template_name => "tools/batchMod.tmpl",
62                  query => $input,
63                  type => "intranet",
64                  authnotrequired => 0,
65                  flagsrequired => {editcatalogue => 1},
66                  });
67
68
69 my $today_iso = C4::Dates->today('iso');
70 $template->param(today_iso => $today_iso);
71
72 my $itemrecord;
73 my $nextop="";
74 my @errors; # store errors found while checking data BEFORE saving item.
75 my $items_display_hashref;
76 my $frameworkcode="";
77 my $tagslib = &GetMarcStructure(1,$frameworkcode);
78
79 #--- ----------------------------------------------------------------------------
80 if ($op eq "action") {
81 #-------------------------------------------------------------------------------
82     my @tags      = $input->param('tag');
83     my @subfields = $input->param('subfield');
84     my @values    = $input->param('field_value');
85     # build indicator hash.
86     my @ind_tag   = $input->param('ind_tag');
87     my @indicator = $input->param('indicator');
88     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
89     my $marcitem = MARC::Record::new_from_xml($xml, 'UTF-8');
90     my $localitem = TransformMarcToKoha( $dbh, $marcitem, "", 'items' );
91
92 #       my @params=$input->param();
93 #       warn @params;
94 #    my $marcitem = TransformHtmlToMarc(\@params,$input);
95         foreach my $itemnumber(@itemnumbers){
96                 my $itemdata=GetItem($itemnumber);
97                 if ($input->param("del")){
98                         DelItemCheck(C4::Context->dbh, $itemdata->{'biblionumber'}, $itemdata->{'itemnumber'})
99                 } else {
100                         my $localmarcitem=Item2Marc($itemdata);
101                         UpdateMarcWith($marcitem,$localmarcitem);
102             eval{my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($localmarcitem,$itemdata->{biblionumber},$itemnumber)};
103                 #       eval{ModItem($localitem,$itemdata->{biblionumber},$itemnumber)};
104                 }
105         }
106         $items_display_hashref=BuildItemsData(@itemnumbers);
107     $nextop="action";
108 }
109
110 #
111 #-------------------------------------------------------------------------------
112 # build screen with existing items. and "new" one
113 #-------------------------------------------------------------------------------
114
115 if ($op eq "show"){
116         my $filefh = $input->upload('uploadfile');
117         my $filecontent = $input->{'filecontent'};
118
119     my @contentlist;
120     if ($filefh){
121         while (my $content=<$filefh>){
122             chomp $content;
123             push @contentlist, $content;
124         }
125
126         switch ($filecontent) {
127             case "barcode_file" {
128                 push @itemnumbers,map{GetItemnumberFromBarcode($_)} @contentlist;
129             }
130
131             case "itemid_file" {
132                 @itemnumbers = @contentlist;
133             }
134         }
135     } else {
136        if ( my $list=$input->param('barcodelist')){
137         push my @barcodelist, split(/\s\n/, $list);
138         push @itemnumbers,map{GetItemnumberFromBarcode($_)} @barcodelist;
139     }
140 }
141         $items_display_hashref=BuildItemsData(@itemnumbers);
142
143 # now, build the item form for entering a new item
144 my @loop_data =();
145 my $i=0;
146 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
147
148 my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
149 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
150
151 foreach my $tag (sort keys %{$tagslib}) {
152 # loop through each subfield
153   foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
154     next if subfield_is_koha_internal_p($subfield);
155     next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "10");
156     my %subfield_data;
157  
158     my $index_subfield = int(rand(1000000)); 
159     if ($subfield eq '@'){
160         $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
161     } else {
162         $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
163     }
164     $subfield_data{tag}        = $tag;
165     $subfield_data{subfield}   = $subfield;
166     $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
167 #   $subfield_data{marc_lib}   = $tagslib->{$tag}->{$subfield}->{lib};
168     $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
169     $subfield_data{mandatory}  = $tagslib->{$tag}->{$subfield}->{mandatory};
170     $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
171     my ($x,$value);
172     $value =~ s/"/&quot;/g;
173     unless ($value) {
174         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
175         # get today date & replace YYYY, MM, DD if provided in the default value
176         my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
177         $value =~ s/YYYY/$year/g;
178         $value =~ s/MM/$month/g;
179         $value =~ s/DD/$day/g;
180     }
181     $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
182     # testing branch value if IndependantBranches.
183
184     my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
185     my $attributes          = qq($attributes_no_value value="$value" );
186     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
187       my @authorised_values;
188       my %authorised_lib;
189       # builds list, depending on authorised value...
190   
191       if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
192           foreach my $thisbranch (@$branches) {
193               push @authorised_values, $thisbranch->{value};
194               $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
195               $value = $thisbranch->{value} if $thisbranch->{selected};
196           }
197       }
198       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
199           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
200           my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
201           $sth->execute;
202           while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
203               push @authorised_values, $itemtype;
204               $authorised_lib{$itemtype} = $description;
205           }
206
207           #---- class_sources
208       }
209       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
210           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
211             
212           my $class_sources = GetClassSources();
213           my $default_source = C4::Context->preference("DefaultClassificationSource");
214           
215           foreach my $class_source (sort keys %$class_sources) {
216               next unless $class_sources->{$class_source}->{'used'} or
217                           ($value and $class_source eq $value)      or
218                           ($class_source eq $default_source);
219               push @authorised_values, $class_source;
220               $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
221           }
222                   $value = $default_source unless ($value);
223
224           #---- "true" authorised value
225       }
226       else {
227           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
228           $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
229           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
230               push @authorised_values, $value;
231               $authorised_lib{$value} = $lib;
232           }
233       }
234       $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
235           -name     => "field_value",
236           -values   => \@authorised_values,
237           -default  => $value,
238           -labels   => \%authorised_lib,
239           -override => 1,
240           -size     => 1,
241           -multiple => 0,
242           -tabindex => 1,
243           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
244           -class    => "input_marceditor",
245       );
246     # it's a thesaurus / authority field
247     }
248     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
249         $subfield_data{marc_value} = "<input type=\"text\" $attributes />
250             <a href=\"#\" class=\"buttonDot\"
251                 onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$tagslib->{$tag}->{$subfield}->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
252     ";
253     # it's a plugin field
254     }
255     elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
256         # opening plugin
257         my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
258         if (do $plugin) {
259                         my $temp;
260             my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
261             my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
262             $subfield_data{marc_value} = qq[<input $attributes
263                 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
264                  onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
265                 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
266                 $javascript];
267         } else {
268             warn "Plugin Failed: $plugin";
269             $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
270         }
271     }
272     elsif ( $tag eq '' ) {       # it's an hidden field
273         $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
274     }
275     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
276         $subfield_data{marc_value} = qq(<input type="text" $attributes />);
277     }
278     elsif ( length($value) > 100
279             or (C4::Context->preference("marcflavour") eq "UNIMARC" and
280                   300 <= $tag && $tag < 400 && $subfield eq 'a' )
281             or (C4::Context->preference("marcflavour") eq "MARC21"  and
282                   500 <= $tag && $tag < 600                     )
283           ) {
284         # oversize field (textarea)
285         $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
286     } else {
287         # it's a standard field
288          $subfield_data{marc_value} = "<input $attributes />";
289     }
290 #   $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
291     push (@loop_data, \%subfield_data);
292     $i++
293   }
294 }
295
296 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
297 $template->param(
298     item             => \@loop_data,
299 );
300 $nextop="action"
301 }
302 $template->param(%$items_display_hashref) if $items_display_hashref;
303 $template->param(
304     op      => $nextop,
305     $op => 1,
306     opisadd => ($nextop eq "saveitem") ? 0 : 1,
307 );
308 foreach my $error (@errors) {
309     $template->param($error => 1);
310 }
311 output_html_with_http_headers $input, $cookie, $template->output;
312 exit;
313
314 sub BuildItemsData{
315         my @itemnumbers=@_;
316                 # now, build existiing item list
317                 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
318                 my @big_array;
319                 #---- finds where items.itemnumber is stored
320                 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
321                 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", "");
322                 foreach my $itemnumber (@itemnumbers){
323                         my $itemdata=GetItem($itemnumber);
324                         my $itemmarc=Item2Marc($itemdata);
325                         my $biblio=GetBiblioData($$itemdata{biblionumber});
326                         my %this_row;
327                         foreach my $field (grep {$_->tag() eq $itemtagfield} $itemmarc->fields()) {
328                                 # loop through each subfield
329                                 if (my $itembranchcode=$field->subfield($branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
330                                                 #verifying rights
331                                                 my $userenv = C4::Context->userenv();
332                                                 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $itembranchcode))){
333                                                                 $this_row{'nomod'}=1;
334                                                 }
335                                 }
336                                 my $tag=$field->tag();
337                                 foreach my $subfield ($field->subfields) {
338                                         my ($subfcode,$subfvalue)=@$subfield;
339                                         next if ($tagslib->{$tag}->{$subfcode}->{tab} ne 10 
340                                                         && $tag        ne $itemtagfield 
341                                                         && $subfcode   ne $itemtagsubfield);
342
343                                         $witness{$subfcode} = $tagslib->{$tag}->{$subfcode}->{lib} if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10);
344                                         if ($tagslib->{$tag}->{$subfcode}->{tab}  eq 10) {
345                                                 $this_row{$subfcode}=GetAuthorisedValueDesc( $tag,
346                                                                         $subfcode, $subfvalue, '', $tagslib) 
347                                                                         || $subfvalue;
348                                         }
349
350                                         $this_row{itemnumber} = $subfvalue if ($tag eq $itemtagfield && $subfcode eq $itemtagsubfield);
351                                 }
352                         }
353                         $this_row{0}=join("\n",@$biblio{qw(title author ISBN)});
354                         $witness{0}="&nbsp;";
355                         if (%this_row) {
356                                 push(@big_array, \%this_row);
357                         }
358                 }
359                 @big_array = sort {$a->{0} cmp $b->{0}} @big_array;
360
361                 # now, construct template !
362                 # First, the existing items for display
363                 my @item_value_loop;
364                 my @witnesscodessorted=sort keys %witness;
365                 for my $row ( @big_array ) {
366                         my %row_data;
367                         my @item_fields = map +{ field => $_ || '' }, @$row{ @witnesscodessorted };
368                         $row_data{item_value} = [ @item_fields ];
369                         $row_data{itemnumber} = $row->{itemnumber};
370                         #reporting this_row values
371                         $row_data{'nomod'} = $row->{'nomod'};
372                         push(@item_value_loop,\%row_data);
373                 }
374                 my @header_loop=map { { header_value=> $witness{$_}} } @witnesscodessorted;
375         return { item_loop        => \@item_value_loop, item_header_loop => \@header_loop };
376 }
377 #BE WARN : it is not the general case 
378 # This function can be OK in the item marc record special case
379 # Where subfield is not repeated
380 # And where we are sure that field should correspond
381 # And $tag>10
382 sub UpdateMarcWith($$){
383   my ($marcfrom,$marcto)=@_;
384   #warn "FROM :",$marcfrom->as_formatted;
385         my (  $itemtag,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", "");
386         my $fieldfrom=$marcfrom->field($itemtag);
387         my @fields_to=$marcto->field($itemtag);
388     foreach my $subfield ($fieldfrom->subfields()){
389                 foreach my $field_to_update (@fields_to){
390                                 $field_to_update->update($$subfield[0]=>$$subfield[1]) if ($$subfield[1]);
391                 }
392     }
393   #warn "TO edited:",$marcto->as_formatted;
394 }