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