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