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