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