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