Bug Fixing : Adding item had a javascript Error.
[koha.git] / cataloguing / additem.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::Context;
27 use C4::Koha; # XXX subfield_is_koha_internal_p
28 use Date::Calc qw(Today);
29
30 use MARC::File::XML;
31
32 sub find_value {
33     my ($tagfield,$insubfield,$record) = @_;
34     my $result;
35     my $indicator;
36     foreach my $field ($record->field($tagfield)) {
37         my @subfields = $field->subfields();
38         foreach my $subfield (@subfields) {
39             if (@$subfield[0] eq $insubfield) {
40                 $result .= @$subfield[1];
41                 $indicator = $field->indicator(1).$field->indicator(2);
42             }
43         }
44     }
45     return($indicator,$result);
46 }
47
48 sub get_item_from_barcode {
49     my ($barcode)=@_;
50     my $dbh=C4::Context->dbh;
51     my $result;
52     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
53     $rq->execute($barcode);
54     ($result)=$rq->fetchrow;
55     return($result);
56 }
57
58 my $input = new CGI;
59 my $dbh = C4::Context->dbh;
60 my $error = $input->param('error');
61 my $biblionumber = $input->param('biblionumber');
62 my $itemnumber = $input->param('itemnumber');
63 warn Data::Dumper::Dumper($input->param());
64 my $op = $input->param('op');
65
66 # find itemtype
67 my $frameworkcode = &GetFrameworkCode($biblionumber);
68
69 my $tagslib = &GetMarcStructure(1,$frameworkcode);
70 my $record = GetMarcBiblio($biblionumber);
71 my $oldrecord = TransformMarcToKoha($dbh,$record);
72 my $itemrecord;
73 my $nextop="additem";
74 my @errors; # store errors found while checking data BEFORE saving item.
75 #-------------------------------------------------------------------------------
76 if ($op eq "additem") {
77 #-------------------------------------------------------------------------------
78     # rebuild
79     my @tags = $input->param('tag');
80     my @subfields = $input->param('subfield');
81     my @values = $input->param('field_value');
82     # build indicator hash.
83     my @ind_tag = $input->param('ind_tag');
84     my @indicator = $input->param('indicator');
85     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
86         my $record=MARC::Record::new_from_xml($xml, 'UTF-8');
87     # if autoBarcode is ON, calculate barcode...
88     if (C4::Context->preference('autoBarcode')) {
89         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
90         unless ($record->field($tagfield)->subfield($tagsubfield)) {
91             my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
92             $sth_barcode->execute;
93             my ($newbarcode) = $sth_barcode->fetchrow;
94             $newbarcode++;
95             # OK, we have the new barcode, now create the entry in MARC record
96             my $fieldItem = $record->field($tagfield);
97             $record->delete_field($fieldItem);
98             $fieldItem->add_subfields($tagsubfield => $newbarcode);
99             $record->insert_fields_ordered($fieldItem);
100         }
101     }
102 # check for item barcode # being unique
103     my $addedolditem = TransformMarcToKoha($dbh,$record);
104     my $exists = get_item_from_barcode($addedolditem->{'barcode'});
105     push @errors,"barcode_not_unique" if($exists);
106     # if barcode exists, don't create, but report The problem.
107     my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItem($record,$biblionumber) unless ($exists);
108     if ($exists) {
109     $nextop = "additem";
110         $itemrecord = $record;
111     } else {
112         $nextop = "additem";
113     }
114 #-------------------------------------------------------------------------------
115 } elsif ($op eq "edititem") {
116 #-------------------------------------------------------------------------------
117 # retrieve item if exist => then, it's a modif
118     $itemrecord = GetMarcItem($biblionumber,$itemnumber);
119     $nextop="saveitem";
120 #-------------------------------------------------------------------------------
121 } elsif ($op eq "delitem") {
122 #-------------------------------------------------------------------------------
123     # check that there is no issue on this item before deletion.
124     my $sth=$dbh->prepare("select * from issues i where i.returndate is null and i.itemnumber=?");
125     $sth->execute($itemnumber);
126     my $onloan=$sth->fetchrow;
127     push @errors,"book_on_loan" if ($onloan); ##error book_on_loan added to template as well
128     if ($onloan){
129     $nextop="additem";
130     } else {
131         &DelItem($dbh,$biblionumber,$itemnumber);
132         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
133         #$nextop="additem";
134     }
135 #-------------------------------------------------------------------------------
136 } elsif ($op eq "saveitem") {
137 #-------------------------------------------------------------------------------
138     # rebuild
139     my @tags = $input->param('tag');
140     my @subfields = $input->param('subfield');
141     my @values = $input->param('field_value');
142     # build indicator hash.
143     my @ind_tag = $input->param('ind_tag');
144     my @indicator = $input->param('indicator');
145   warn "tags :@tags"  ;
146   warn "subfields :@subfields"  ;
147   warn "values :@values"  ;
148 #    my $itemnumber = $input->param('itemnumber');
149     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
150         my $itemrecord=MARC::Record::new_from_xml($xml, 'UTF-8');
151 # MARC::Record builded => now, record in DB
152 # warn "R: ".$record->as_formatted;
153     my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItem($itemrecord,$biblionumber,$itemnumber,0);
154     $itemnumber="";
155     $nextop="additem";
156 }
157
158 #
159 #-------------------------------------------------------------------------------
160 # build screen with existing items. and "new" one
161 #-------------------------------------------------------------------------------
162 my ($template, $loggedinuser, $cookie)
163     = get_template_and_user({template_name => "cataloguing/additem.tmpl",
164                  query => $input,
165                  type => "intranet",
166                  authnotrequired => 0,
167                  flagsrequired => {editcatalogue => 1},
168                  debug => 1,
169                  });
170
171 # now, build existiing item list
172 my $temp = GetMarcBiblio( $biblionumber );
173 my @fields = $temp->fields();
174 #my @fields = $record->fields();
175 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
176 my @big_array;
177 #---- finds where items.itemnumber is stored
178 my ($itemtagfield,$itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber",$frameworkcode);
179 my ($branchtagfield,$branchtagsubfield) = &GetMarcFromKohaField("items.homebranch",$frameworkcode);
180
181 foreach my $field (@fields) {
182     next if ($field->tag()<10);
183     my @subf=$field->subfields;
184     my %this_row;
185 # loop through each subfield
186     for my $i (0..$#subf) {
187         next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab} ne 10 
188                 && ($field->tag() ne $itemtagfield 
189                 && $subf[$i][0] ne $itemtagsubfield));
190
191         $witness{$subf[$i][0]} = $tagslib->{$field->tag()}->{$subf[$i][0]}->{lib} if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10);
192
193         $this_row{$subf[$i][0]} =$subf[$i][1] if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10);
194         
195                 if (($field->tag eq $branchtagfield) && ($subf[$i][$0] eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
196             #verifying rights
197             my $userenv = C4::Context->userenv();
198             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subf[$i][1]))){
199                     $this_row{'nomod'}=1;
200             }
201         }
202         $this_row{itemnumber} = $subf[$i][1] if ($field->tag() eq $itemtagfield && $subf[$i][0] eq $itemtagsubfield);
203     }
204     if (%this_row) {
205         push(@big_array, \%this_row);
206     }
207 }
208 #fill big_row with missing data
209 foreach my $subfield_code  (keys(%witness)) {
210     for (my $i=0;$i<=$#big_array;$i++) {
211         $big_array[$i]{$subfield_code}="&nbsp;" unless ($big_array[$i]{$subfield_code});
212     }
213 }
214 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
215 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
216
217 # now, construct template !
218 # First, the existing items for display
219 my @item_value_loop;
220 my @header_value_loop;
221 for (my $i=0;$i<=$#big_array; $i++) {
222     my $items_data;
223     foreach my $subfield_code (sort keys(%witness)) {
224         $items_data .="<td>".$big_array[$i]{$subfield_code}."</td>";
225     }
226     my %row_data;
227     $items_data =~ s/"/&quot;/g;
228     $row_data{item_value} = $items_data;
229     $row_data{itemnumber} = $big_array[$i]->{itemnumber};
230     #reporting this_row values
231     $row_data{'nomod'} = $big_array[$i]{'nomod'};
232     push(@item_value_loop,\%row_data);
233 }
234 foreach my $subfield_code (sort keys(%witness)) {
235     my %header_value;
236     $header_value{header_value} = $witness{$subfield_code};
237     push(@header_value_loop, \%header_value);
238 }
239
240 # now, build the item form for entering a new item
241 my @loop_data =();
242 my $i=0;
243 my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
244
245 foreach my $tag (sort keys %{$tagslib}) {
246   my $previous_tag = '';
247 # loop through each subfield
248   foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
249     next if subfield_is_koha_internal_p($subfield);
250     next if ($tagslib->{$tag}->{$subfield}->{'tab'}  ne "10");
251     my %subfield_data;
252  
253     my $index_subfield= int(rand(1000000)); 
254     if($subfield eq '@'){
255         $subfield_data{id} = "tag_".$tag."_subfield_0_".$index_subfield;
256     } else {
257          $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".$index_subfield;
258     }
259     $subfield_data{tag}=$tag;
260     $subfield_data{subfield}=$subfield;
261     $subfield_data{random}=int(rand(1000000)); 
262 #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
263     $subfield_data{marc_lib}="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".$tagslib->{$tag}->{$subfield}->{lib}."</span>";
264     $subfield_data{mandatory}=$tagslib->{$tag}->{$subfield}->{mandatory};
265     $subfield_data{repeatable}=$tagslib->{$tag}->{$subfield}->{repeatable};
266     my ($x,$value);
267     ($x,$value) = find_value($tag,$subfield,$itemrecord) if ($itemrecord);
268     $value =~ s/"/&quot;/g;
269     unless ($value) {
270         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
271
272         # get today date & replace YYYY, MM, DD if provided in the default value
273         my ( $year, $month, $day ) = Today();
274         $month = sprintf( "%02d", $month );
275         $day   = sprintf( "%02d", $day );
276         $value =~ s/YYYY/$year/g;
277         $value =~ s/MM/$month/g;
278         $value =~ s/DD/$day/g;
279     }
280     $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} % 2 == 1) and $value ne '');
281     #testing branch value if IndependantBranches.
282     my $test = (C4::Context->preference("IndependantBranches")) &&
283               ($tag eq $branchtagfield) && ($subfield eq $branchtagsubfield) &&
284               (C4::Context->userenv->{flags} != 1) && ($value) && ($value ne C4::Context->userenv->{branch}) ;
285 #         print $input->redirect(".pl?biblionumber=$biblionumber") if ($test);
286         # search for itemcallnumber if applicable
287     if (!$value && $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber' && C4::Context->preference('itemcallnumber')) {
288       my $CNtag = substr(C4::Context->preference('itemcallnumber'),0,3);
289       my $CNsubfield = substr(C4::Context->preference('itemcallnumber'),3,1);
290                         my $CNsubfield2 = substr(C4::Context->preference('itemcallnumber'),4,1);
291                         my $temp2 = $temp->field($CNtag);
292                         if ($temp2) {
293                                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
294 #remove any trailing space incase one subfield is used
295         $value=~s/^\s+|\s+$//g;
296       }
297     }
298     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
299       my @authorised_values;
300       my %authorised_lib;
301       my $dbh=C4::Context->dbh;   
302   
303       # builds list, depending on authorised value...
304   
305       #---- branch
306       if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
307           my $sth =
308             $dbh->prepare(
309               "select branchcode,branchname from branches order by branchname");
310           $sth->execute;
311           push @authorised_values, ""
312             unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
313   
314           while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
315               push @authorised_values, $branchcode;
316               $authorised_lib{$branchcode} = $branchname;
317           }
318   
319           #----- itemtypes
320       }
321       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
322           my $sth =
323             $dbh->prepare(
324               "select itemtype,description from itemtypes order by description");
325           $sth->execute;
326           push @authorised_values, ""
327             unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
328             
329           my $itemtype;
330           
331           while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
332               push @authorised_values, $itemtype;
333               $authorised_lib{$itemtype} = $description;
334           }
335           $value = $itemtype unless ($value);
336   
337           #---- "true" authorised value
338       }
339       else {
340           $authorised_values_sth->execute(
341               $tagslib->{$tag}->{$subfield}->{authorised_value} );
342   
343           push @authorised_values, ""
344             unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
345   
346           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
347               push @authorised_values, $value;
348               $authorised_lib{$value} = $lib;
349           }
350       }
351       $subfield_data{marc_value} =CGI::scrolling_list(
352           -name     => "field_value",
353           -values   => \@authorised_values,
354           -default  => $value,
355           -labels   => \%authorised_lib,
356           -override => 1,
357           -size     => 1,
358           -multiple => 0,
359           -tabindex => 1,
360           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
361           -class    => "input_marceditor",
362       );
363     # it's a thesaurus / authority field
364     }
365     elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) {
366         $subfield_data{marc_value} =
367             "<input type=\"text\"
368                     id=\"".$subfield_data{id}."\"
369                     name=\"field_value\"
370                     value=\"$value\"
371                     class=\"input_marceditor\"
372                     tabindex=\"1\"
373                     size=\"67\"
374                     maxlength=\"255\" 
375                     \/>
376                     <a href=\"#\" class=\"buttonDot\"
377                         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>
378     ";
379     # it's a plugin field
380     }
381     elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) {
382
383         # opening plugin. Just check wether we are on a developper computer on a production one
384         # (the cgidir differs)
385         my $cgidir = C4::Context->intranetdir . "/cgi-bin/cataloguing/value_builder";
386         unless ( opendir( DIR, "$cgidir" ) ) {
387             $cgidir = C4::Context->intranetdir . "/cataloguing/value_builder";
388         }
389         my $plugin = $cgidir . "/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
390         do $plugin || die "Plugin Failed: ".$plugin;
391         my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
392         my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, \@loop_data );
393 #         my ( $function_name, $javascript,$extended_param );
394         
395         $subfield_data{marc_value} =
396                 "<input tabindex=\"1\"
397                         type=\"text\"
398                         id=\"".$subfield_data{id}."\"
399                         name=\"field_value\"
400                         value=\"$value\"
401                         class=\"input_marceditor\"
402                         onfocus=\"Focus$function_name(".$subfield_data{random}.")\"
403                         size=\"67\"
404                         maxlength=\"255\" 
405                         onblur=\"Blur$function_name(".$subfield_data{random}."); \" \/>
406                         <a href=\"#\" class=\"buttonDot\" onclick=\"Clic$function_name('$subfield_data{id}'; return false;)\" title=\"Tag Editor\">...</a>
407                 $javascript";
408         # it's an hidden field
409     }
410     elsif ( $tag eq '' ) {
411         $subfield_data{marc_value} =
412             "<input tabindex=\"1\"
413                     type=\"hidden\"
414                     id=\"".$subfield_data{id}."\"
415                     name=\"field_value\"
416                     size=\"67\"
417                     maxlength=\"255\" 
418                     value=\"$value\" \/>
419             ";
420     }
421     elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) {
422         $subfield_data{marc_value} =
423             "<input type=\"text\"
424                     id=\"".$subfield_data{id}."\"
425                     name=\"field_value\"
426                     class=\"input_marceditor\"
427                     tabindex=\"1\"
428                     size=\"67\"
429                     maxlength=\"255\" 
430                     value=\"$value\"
431             \/>";
432
433         # it's a standard field
434     }
435     else {
436         if (
437             length($value) > 100
438             or
439             ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300
440                 and $tag < 400 && $subfield eq 'a' )
441             or (    $tag >= 500
442                 and $tag < 600
443                 && C4::Context->preference("marcflavour") eq "MARC21" )
444           )
445         {
446             $subfield_data{marc_value} =
447                 "<textarea cols=\"70\"
448                            rows=\"4\"
449                            id=\"".$subfield_data{id}."\"
450                            name=\"field_value\"
451                            class=\"input_marceditor\"
452                            tabindex=\"1\"
453                             size=\"67\"
454                             maxlength=\"255\" 
455                            >$value</textarea>
456                 ";
457         }
458         else {
459             $subfield_data{marc_value} =
460                 "<input type=\"text\"
461                         id=\"".$subfield_data{id}."\"
462                         name=\"field_value\"
463                         value=\"$value\"
464                         tabindex=\"1\"
465                         size=\"67\"
466                         maxlength=\"255\" 
467                         class=\"input_marceditor\"
468                 \/>
469                 ";
470         }
471     }
472 #        $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
473         push(@loop_data, \%subfield_data);
474         $i++
475     }
476 }
477
478 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
479 $template->param( title => $record->title() ) if ($record ne "-1");
480 $template->param(item_loop => \@item_value_loop,
481                         item_header_loop => \@header_value_loop,
482                         biblionumber => $biblionumber,
483                         title => $oldrecord->{title},
484                         author => $oldrecord->{author},
485                         item => \@loop_data,
486                         itemnumber => $itemnumber,
487                         itemtagfield => $itemtagfield,
488                         itemtagsubfield =>$itemtagsubfield,
489                         op => $nextop,
490                         opisadd => ($nextop eq "saveitem")?0:1);
491 foreach my $error (@errors) {
492     $template->param($error => 1);
493 }
494 output_html_with_http_headers $input, $cookie, $template->output;