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