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