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