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