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