plugin rewrited to works with addbiblio.
[koha.git] / cataloguing / additem.pl
1 #!/usr/bin/perl
2
3 # $Id$
4
5 # Copyright 2000-2002 Katipo Communications
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 USA
21
22 use CGI;
23 use strict;
24 use C4::Auth;
25 use C4::Output;
26 use C4::Biblio;
27 use C4::Context;
28 use C4::Koha; # XXX subfield_is_koha_internal_p
29
30 use MARC::File::XML;
31
32 sub find_value {
33     my ($tagfield,$insubfield,$record) = @_;
34     my $result;
35     my $indicator;
36     foreach my $field ($record->field($tagfield)) {
37         my @subfields = $field->subfields();
38         foreach my $subfield (@subfields) {
39             if (@$subfield[0] eq $insubfield) {
40                 $result .= @$subfield[1];
41                 $indicator = $field->indicator(1).$field->indicator(2);
42             }
43         }
44     }
45     return($indicator,$result);
46 }
47
48 sub get_item_from_barcode {
49     my ($barcode)=@_;
50     my $dbh=C4::Context->dbh;
51     my $result;
52     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
53     $rq->execute($barcode);
54     ($result)=$rq->fetchrow;
55     return($result);
56 }
57
58 my $input = new CGI;
59 my $dbh = C4::Context->dbh;
60 my $error = $input->param('error');
61 my $biblionumber = $input->param('biblionumber');
62 my $itemnumber = $input->param('itemnumber');
63
64 my $op = $input->param('op');
65
66 # find itemtype
67 my $frameworkcode = &GetFrameworkCode($biblionumber);
68
69 my $tagslib = &GetMarcStructure(1,$frameworkcode);
70 my $record = GetMarcBiblio($biblionumber);
71 warn "==>".$record->as_formatted;
72 my $oldrecord = TransformMarcToKoha($dbh,$record);
73 my $itemrecord;
74 my $nextop="additem";
75 my @errors; # store errors found while checking data BEFORE saving item.
76 #-------------------------------------------------------------------------------
77 if ($op eq "additem") {
78 #-------------------------------------------------------------------------------
79     # rebuild
80     my @tags = $input->param('tag');
81     my @subfields = $input->param('subfield');
82     my @values = $input->param('field_value');
83     # build indicator hash.
84     my @ind_tag = $input->param('ind_tag');
85     my @indicator = $input->param('indicator');
86     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
87         my $record=MARC::Record::new_from_xml($xml, 'UTF-8');
88     # if autoBarcode is ON, calculate barcode...
89     if (C4::Context->preference('autoBarcode')) {
90         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
91         unless ($record->field($tagfield)->subfield($tagsubfield)) {
92             my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
93             $sth_barcode->execute;
94             my ($newbarcode) = $sth_barcode->fetchrow;
95             $newbarcode++;
96             # OK, we have the new barcode, now create the entry in MARC record
97             my $fieldItem = $record->field($tagfield);
98             $record->delete_field($fieldItem);
99             $fieldItem->add_subfields($tagsubfield => $newbarcode);
100             $record->insert_fields_ordered($fieldItem);
101         }
102     }
103 # check for item barcode # being unique
104     my $addedolditem = TransformMarcToKoha($dbh,$record);
105     my $exists = get_item_from_barcode($addedolditem->{'barcode'});
106     push @errors,"barcode_not_unique" if($exists);
107     # if barcode exists, don't create, but report The problem.
108     my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItem($record,$biblionumber) unless ($exists);
109     if ($exists) {
110     $nextop = "additem";
111         $itemrecord = $record;
112     } else {
113         $nextop = "additem";
114     }
115 #-------------------------------------------------------------------------------
116 } elsif ($op eq "edititem") {
117 #-------------------------------------------------------------------------------
118 # retrieve item if exist => then, it's a modif
119     $itemrecord = GetMarcItem($biblionumber,$itemnumber);
120     $nextop="saveitem";
121 #-------------------------------------------------------------------------------
122 } elsif ($op eq "delitem") {
123 #-------------------------------------------------------------------------------
124     # check that there is no issue on this item before deletion.
125     my $sth=$dbh->prepare("select * from issues i where i.returndate is null and i.itemnumber=?");
126     $sth->execute($itemnumber);
127     my $onloan=$sth->fetchrow;
128     push @errors,"book_on_loan" if ($onloan); ##error book_on_loan added to template as well
129     if ($onloan){
130     $nextop="additem";
131     } else {
132         &DelItem($biblionumber,$itemnumber);
133         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
134         #$nextop="additem";
135     }
136 #-------------------------------------------------------------------------------
137 } elsif ($op eq "saveitem") {
138 #-------------------------------------------------------------------------------
139     # rebuild
140     my @tags = $input->param('tag');
141     my @subfields = $input->param('subfield');
142     my @values = $input->param('field_value');
143     # build indicator hash.
144     my @ind_tag = $input->param('ind_tag');
145     my @indicator = $input->param('indicator');
146 #    my $itemnumber = $input->param('itemnumber');
147     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
148         my $itemrecord=MARC::Record::new_from_xml($xml, 'UTF-8');
149 # MARC::Record builded => now, record in DB
150 # warn "R: ".$record->as_formatted;
151     my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItem($itemrecord,$biblionumber,$itemnumber,0);
152     $itemnumber="";
153     $nextop="additem";
154 }
155
156 #
157 #-------------------------------------------------------------------------------
158 # build screen with existing items. and "new" one
159 #-------------------------------------------------------------------------------
160 my ($template, $loggedinuser, $cookie)
161     = get_template_and_user({template_name => "cataloguing/additem.tmpl",
162                  query => $input,
163                  type => "intranet",
164                  authnotrequired => 0,
165                  flagsrequired => {editcatalogue => 1},
166                  debug => 1,
167                  });
168
169 my %indicators;
170 $indicators{995}='  ';
171 # now, build existiing item list
172 my $temp = GetMarcBiblio( $biblionumber );
173 my @fields = $temp->fields();
174 #my @fields = $record->fields();
175 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
176 my @big_array;
177 #---- finds where items.itemnumber is stored
178 my ($itemtagfield,$itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber",$frameworkcode);
179 my ($branchtagfield,$branchtagsubfield) = &GetMarcFromKohaField("items.homebranch",$frameworkcode);
180
181 foreach my $field (@fields) {
182     next if ($field->tag()<10);
183     my @subf=$field->subfields;
184     my %this_row;
185 # loop through each subfield
186     for my $i (0..$#subf) {
187         next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  ne 10 && ($field->tag() ne $itemtagfield && $subf[$i][0] ne $itemtagsubfield));
188         $witness{$subf[$i][0]} = $tagslib->{$field->tag()}->{$subf[$i][0]}->{lib} if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10);
189         $this_row{$subf[$i][0]} =$subf[$i][1] if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  eq 10);
190         if (($field->tag eq $branchtagfield) && ($subf[$i][$0] eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
191             #verifying rights
192             my $userenv = C4::Context->userenv;
193             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subf[$i][1]))){
194                     $this_row{'nomod'}=1;
195             }
196         }
197         $this_row{itemnumber} = $subf[$i][1] if ($field->tag() eq $itemtagfield && $subf[$i][0] eq $itemtagsubfield);
198     }
199     if (%this_row) {
200         push(@big_array, \%this_row);
201     }
202 }
203 #fill big_row with missing datas
204 foreach my $subfield_code  (keys(%witness)) {
205     for (my $i=0;$i<=$#big_array;$i++) {
206         $big_array[$i]{$subfield_code}="&nbsp;" unless ($big_array[$i]{$subfield_code});
207     }
208 }
209 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
210 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
211
212 # now, construct template !
213 my @item_value_loop;
214 my @header_value_loop;
215 for (my $i=0;$i<=$#big_array; $i++) {
216     my $items_data;
217     foreach my $subfield_code (sort keys(%witness)) {
218         $items_data .="<td>".$big_array[$i]{$subfield_code}."</td>";
219     }
220     my %row_data;
221     $items_data =~ s/"/&quot;/g;
222     $row_data{item_value} = $items_data;
223     $row_data{itemnumber} = $big_array[$i]->{itemnumber};
224     #reporting this_row values
225     $row_data{'nomod'} = $big_array[$i]{'nomod'};
226     push(@item_value_loop,\%row_data);
227 }
228 foreach my $subfield_code (sort keys(%witness)) {
229     my %header_value;
230     $header_value{header_value} = $witness{$subfield_code};
231     push(@header_value_loop, \%header_value);
232 }
233
234 # next item form
235 my @loop_data =();
236 my $i=0;
237 my $authorised_values_sth = $dbh->prepare("select authorised_value,lib from authorised_values where category=? order by lib");
238
239 foreach my $tag (sort keys %{$tagslib}) {
240   my $previous_tag = '';
241 # loop through each subfield
242   foreach my $subfield (sort keys %{$tagslib->{$tag}}) {
243     next if subfield_is_koha_internal_p($subfield);
244     next if ($tagslib->{$tag}->{$subfield}->{'tab'}  ne "10");
245     my %subfield_data;
246     $subfield_data{tag}=$tag;
247     $subfield_data{subfield}=$subfield;
248 #        $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
249     $subfield_data{marc_lib}="<span id=\"error$i\" title=\"".$tagslib->{$tag}->{$subfield}->{lib}."\">".substr($tagslib->{$tag}->{$subfield}->{lib},0,12)."</span>";
250     $subfield_data{mandatory}=$tagslib->{$tag}->{$subfield}->{mandatory};
251     $subfield_data{repeatable}=$tagslib->{$tag}->{$subfield}->{repeatable};
252     $subfield_data{hidden}= "display:none" if $tagslib->{$tag}->{$subfield}->{hidden};
253     my ($x,$value);
254     ($x,$value) = find_value($tag,$subfield,$itemrecord) if ($itemrecord);
255     $value =~ s/"/&quot;/g;
256     #testing branch value if IndependantBranches.
257     my $test = (C4::Context->preference("IndependantBranches")) &&
258               ($tag eq $branchtagfield) && ($subfield eq $branchtagsubfield) &&
259               (C4::Context->userenv->{flags} != 1) && ($value) && ($value ne C4::Context->userenv->{branch}) ;
260 #         print $input->redirect(".pl?biblionumber=$biblionumber") if ($test);
261         # search for itemcallnumber if applicable
262     if (!$value && $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber' && C4::Context->preference('itemcallnumber')) {
263       my $CNtag = substr(C4::Context->preference('itemcallnumber'),0,3);
264       my $CNsubfield = substr(C4::Context->preference('itemcallnumber'),3,1);
265                         my $CNsubfield2 = substr(C4::Context->preference('itemcallnumber'),4,1);
266                         my $temp2 = $temp->field($CNtag);
267                         if ($temp2) {
268                                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
269 #remove any trailing space incase one subfield is used
270         $value=~s/^\s+|\s+$//g;
271       }
272     }
273     if ($tagslib->{$tag}->{$subfield}->{authorised_value}) {
274       my @authorised_values;
275       my %authorised_lib;
276       # builds list, depending on authorised value...
277       #---- branch
278       if ($tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
279         if ((C4::Context->preference("IndependantBranches")) && (C4::Context->userenv->{flags} != 1)){
280           my $sth=$dbh->prepare("select branchcode,branchname from branches where branchcode = ? order by branchname");
281           $sth->execute(C4::Context->userenv->{branch});
282           push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
283           while (my ($branchcode,$branchname) = $sth->fetchrow_array) {
284               push @authorised_values, $branchcode;
285               $authorised_lib{$branchcode}=$branchname;
286           }
287         } else {
288           my $sth=$dbh->prepare("select branchcode,branchname from branches order by branchname");
289           $sth->execute;
290           push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
291           while (my ($branchcode,$branchname) = $sth->fetchrow_array) {
292               push @authorised_values, $branchcode;
293               $authorised_lib{$branchcode}=$branchname;
294           }
295         }
296         #----- itemtypes
297         } elsif ($tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes") {
298             my $sth=$dbh->prepare("select itemtype,description from itemtypes order by description");
299             $sth->execute;
300             push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
301             while (my ($itemtype,$description) = $sth->fetchrow_array) {
302                 push @authorised_values, $itemtype;
303                 $authorised_lib{$itemtype}=$description;
304             }
305       #---- "true" authorised value
306       } else {
307           $authorised_values_sth->execute($tagslib->{$tag}->{$subfield}->{authorised_value});
308           push @authorised_values, "" unless ($tagslib->{$tag}->{$subfield}->{mandatory});
309           while (my ($authvalue,$lib) = $authorised_values_sth->fetchrow_array) {
310               push @authorised_values, $authvalue;
311               $authorised_lib{$authvalue}=$lib;
312           }
313       }
314       $subfield_data{marc_value}= CGI::scrolling_list(-name=>'field_value',
315                                                                   -values=> \@authorised_values,
316                                                                   -default=>"$value",
317                                                                   -labels => \%authorised_lib,
318                                                                   -size=>1,
319                                                                     -tabindex=>'',
320                                                                   -multiple=>0,
321                                                                   );
322     } elsif ($tagslib->{$tag}->{$subfield}->{thesaurus_category}) {
323       $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\"  size=47 maxlength=255> <a href=\"javascript:Dopop('cataloguing/thesaurus_popup.pl?category=$tagslib->{$tag}->{$subfield}->{thesaurus_category}&index=$i',$i)\">...</a>";
324           #"
325     } elsif ($tagslib->{$tag}->{$subfield}->{'value_builder'}) {
326       my $plugin="value_builder/".$tagslib->{$tag}->{$subfield}->{'value_builder'};
327       require $plugin;
328       my $extended_param = plugin_parameters($dbh,$record,$tagslib,$i,0);
329       my ($function_name,$javascript) = plugin_javascript($dbh,$record,$tagslib,$i,0);
330       $subfield_data{marc_value}="<input type=\"text\" value=\"$value\" name=\"field_value\"  size=47 maxlength=255 OnFocus=\"javascript:Focus$function_name($i)\" OnBlur=\"javascript:Blur$function_name($i)\"> <a href=\"javascript:Clic$function_name($i)\">...</a> $javascript";
331     } else {
332       $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\" value=\"$value\" size=50 maxlength=255>";
333     }
334 #        $subfield_data{marc_value}="<input type=\"text\" name=\"field_value\">";
335         push(@loop_data, \%subfield_data);
336         $i++
337     }
338 }
339
340 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
341 $template->param( title => $record->title() ) if ($record ne "-1");
342 $template->param(item_loop => \@item_value_loop,
343                         item_header_loop => \@header_value_loop,
344                         biblionumber => $biblionumber,
345                         title => $oldrecord->{title},
346                         author => $oldrecord->{author},
347                         item => \@loop_data,
348                         itemnumber => $itemnumber,
349                         itemtagfield => $itemtagfield,
350                         itemtagsubfield =>$itemtagsubfield,
351                         op => $nextop,
352                         opisadd => ($nextop eq "saveitem")?0:1);
353 foreach my $error (@errors) {
354     $template->param($error => 1);
355 }
356 output_html_with_http_headers $input, $cookie, $template->output;