Merge branch 'new/bug_5690' into kcmaster
[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
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use strict;
22 #use warnings; FIXME - Bug 2505
23 use CGI;
24 use C4::Auth;
25 use C4::Output;
26 use C4::Biblio;
27 use C4::Items;
28 use C4::Context;
29 use C4::Koha; # XXX subfield_is_koha_internal_p
30 use C4::Branch; # XXX subfield_is_koha_internal_p
31 use C4::ClassSource;
32 use C4::Dates;
33 use List::MoreUtils qw/any/;
34
35 use MARC::File::XML;
36
37 my $dbh = C4::Context->dbh;
38
39 sub find_value {
40     my ($tagfield,$insubfield,$record) = @_;
41     my $result;
42     my $indicator;
43     foreach my $field ($record->field($tagfield)) {
44         my @subfields = $field->subfields();
45         foreach my $subfield (@subfields) {
46             if (@$subfield[0] eq $insubfield) {
47                 $result .= @$subfield[1];
48                 $indicator = $field->indicator(1).$field->indicator(2);
49             }
50         }
51     }
52     return($indicator,$result);
53 }
54
55 sub get_item_from_barcode {
56     my ($barcode)=@_;
57     my $dbh=C4::Context->dbh;
58     my $result;
59     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
60     $rq->execute($barcode);
61     ($result)=$rq->fetchrow;
62     return($result);
63 }
64
65 sub set_item_default_location {
66     my $itemnumber = shift;
67     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
68         my $item = GetItem( $itemnumber );
69         $item->{'permanent_location'} = $item->{'location'};
70         $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
71         ModItem( $item, undef, $itemnumber);
72     }
73 }
74
75 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
76 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
77 sub _increment_barcode {
78     my ($record, $frameworkcode) = @_;
79     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
80     unless ($record->field($tagfield)->subfield($tagsubfield)) {
81         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
82         $sth_barcode->execute;
83         my ($newbarcode) = $sth_barcode->fetchrow;
84         $newbarcode++;
85         # OK, we have the new barcode, now create the entry in MARC record
86         my $fieldItem = $record->field($tagfield);
87         $record->delete_field($fieldItem);
88         $fieldItem->add_subfields($tagsubfield => $newbarcode);
89         $record->insert_fields_ordered($fieldItem);
90     }
91     return $record;
92 }
93
94
95 sub generate_subfield_form {
96         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $today_iso, $biblionumber, $temp, $loop_data, $i) = @_;
97         
98         my %subfield_data;
99         my $dbh = C4::Context->dbh;        
100         my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
101         
102         my $index_subfield = int(rand(1000000)); 
103         if ($subfieldtag eq '@'){
104             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
105         } else {
106             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
107         }
108         
109         $subfield_data{tag}        = $tag;
110         $subfield_data{subfield}   = $subfieldtag;
111         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
112         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
113         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
114         $subfield_data{repeatable} = $subfieldlib->{repeatable};
115         
116         $value =~ s/"/&quot;/g;
117         if ( ! defined( $value ) || $value eq '')  {
118             $value = $subfieldlib->{defaultvalue};
119             # get today date & replace YYYY, MM, DD if provided in the default value
120             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
121             $value =~ s/YYYY/$year/g;
122             $value =~ s/MM/$month/g;
123             $value =~ s/DD/$day/g;
124         }
125         
126         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} < -4));
127         
128         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
129         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
130             my $CNtag       = substr($pref_itemcallnumber, 0, 3);
131             my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
132             my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
133             my $temp2 = $temp->field($CNtag);
134             if ($temp2) {
135                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
136                 #remove any trailing space incase one subfield is used
137                 $value =~ s/^\s+|\s+$//g;
138             }
139         }
140         
141         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
142         my $attributes          = qq($attributes_no_value value="$value" );
143         
144         if ( $subfieldlib->{authorised_value} ) {
145             my @authorised_values;
146             my %authorised_lib;
147             # builds list, depending on authorised value...
148             if ( $subfieldlib->{authorised_value} eq "branches" ) {
149                 foreach my $thisbranch (@$branches) {
150                     push @authorised_values, $thisbranch->{value};
151                     $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
152                     $value = $thisbranch->{value} if $thisbranch->{selected};
153                 }
154             }
155             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
156                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
157                   my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
158                   $sth->execute;
159                   while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
160                       push @authorised_values, $itemtype;
161                       $authorised_lib{$itemtype} = $description;
162                   }
163         
164                   unless ( $value ) {
165                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
166                       $itype_sth->execute( $biblionumber );
167                       ( $value ) = $itype_sth->fetchrow_array;
168                   }
169           
170                   #---- class_sources
171             }
172             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
173                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
174                     
175                   my $class_sources = GetClassSources();
176                   my $default_source = C4::Context->preference("DefaultClassificationSource");
177                   
178                   foreach my $class_source (sort keys %$class_sources) {
179                       next unless $class_sources->{$class_source}->{'used'} or
180                                   ($value and $class_source eq $value)      or
181                                   ($class_source eq $default_source);
182                       push @authorised_values, $class_source;
183                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
184                   }
185                           $value = $default_source unless ($value);
186         
187                   #---- "true" authorised value
188             }
189             else {
190                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
191                   $authorised_values_sth->execute( $subfieldlib->{authorised_value} );
192                   while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
193                       push @authorised_values, $value;
194                       $authorised_lib{$value} = $lib;
195                   }
196             }
197
198             $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
199                   -name     => "field_value",
200                   -values   => \@authorised_values,
201                   -default  => $value,
202                   -labels   => \%authorised_lib,
203                   -override => 1,
204                   -size     => 1,
205                   -multiple => 0,
206                   -tabindex => 1,
207                   -id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
208                   -class    => "input_marceditor",
209             );
210
211             # it's a thesaurus / authority field
212         }
213         elsif ( $subfieldlib->{authtypecode} ) {
214                 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
215                     <a href=\"#\" class=\"buttonDot\"
216                         onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$subfieldlib->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
217             ";
218             # it's a plugin field
219         }
220         elsif ( $subfieldlib->{value_builder} ) {
221                 # opening plugin
222                 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $subfieldlib->{'value_builder'};
223                 if (do $plugin) {
224                     my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
225                     my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
226                     my $change = index($javascript, 'function Change') > -1 ?
227                         "return Change$function_name($subfield_data{random}, '$subfield_data{id}');" :
228                         'return 1;';
229                     $subfield_data{marc_value} = qq[<input $attributes
230                         onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
231                         onchange=" $change"
232                          onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
233                         <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
234                         $javascript];
235                 } else {
236                     warn "Plugin Failed: $plugin";
237                     $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
238                 }
239         }
240         elsif ( $tag eq '' ) {       # it's an hidden field
241             $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
242         }
243         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
244             $subfield_data{marc_value} = qq(<input type="text" $attributes />);
245         }
246         elsif ( length($value) > 100
247                     or (C4::Context->preference("marcflavour") eq "UNIMARC" and
248                           300 <= $tag && $tag < 400 && $subfieldtag eq 'a' )
249                     or (C4::Context->preference("marcflavour") eq "MARC21"  and
250                           500 <= $tag && $tag < 600                     )
251                   ) {
252             # oversize field (textarea)
253             $subfield_data{marc_value} = "<textarea $attributes_no_value>$value</textarea>\n";
254         } else {
255            # it's a standard field
256            $subfield_data{marc_value} = "<input $attributes />";
257         }
258         
259         return \%subfield_data;
260 }
261
262
263 my $input        = new CGI;
264 my $dbh          = C4::Context->dbh;
265 my $error        = $input->param('error');
266 my $biblionumber = $input->param('biblionumber');
267 my $itemnumber   = $input->param('itemnumber');
268 my $op           = $input->param('op');
269
270 my $frameworkcode = &GetFrameworkCode($biblionumber);
271
272 # Defining which userflag is needing according to the framework currently used
273 my $userflags;
274 if (defined $input->param('frameworkcode')) {
275     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
276 }
277
278 if (not defined $userflags) {
279     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
280 }
281
282 my ($template, $loggedinuser, $cookie)
283     = get_template_and_user({template_name => "cataloguing/additem.tmpl",
284                  query => $input,
285                  type => "intranet",
286                  authnotrequired => 0,
287                  flagsrequired => {editcatalogue => $userflags},
288                  debug => 1,
289                  });
290
291
292 my $today_iso = C4::Dates->today('iso');
293 $template->param(today_iso => $today_iso);
294
295 my $tagslib = &GetMarcStructure(1,$frameworkcode);
296 my $record = GetMarcBiblio($biblionumber);
297 my $oldrecord = TransformMarcToKoha($dbh,$record);
298 my $itemrecord;
299 my $nextop="additem";
300 my @errors; # store errors found while checking data BEFORE saving item.
301 #-------------------------------------------------------------------------------
302 if ($op eq "additem") {
303 #-------------------------------------------------------------------------------
304     # rebuild
305     my @tags      = $input->param('tag');
306     my @subfields = $input->param('subfield');
307     my @values    = $input->param('field_value');
308     # build indicator hash.
309     my @ind_tag   = $input->param('ind_tag');
310     my @indicator = $input->param('indicator');
311     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
312     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
313
314     # type of add
315     my $add_submit                 = $input->param('add_submit');
316     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
317     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
318     my $number_of_copies           = $input->param('number_of_copies');
319
320     if (C4::Context->preference('autoBarcode') eq 'incremental') {
321         $record = _increment_barcode($record, $frameworkcode);
322     }
323
324     my $addedolditem = TransformMarcToKoha($dbh,$record);
325
326     # If we have to add or add & duplicate, we add the item
327     if ($add_submit || $add_duplicate_submit) {
328         # check for item barcode # being unique
329         my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
330         push @errors,"barcode_not_unique" if($exist_itemnumber);
331         # if barcode exists, don't create, but report The problem.
332     unless ($exist_itemnumber) {
333             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
334         set_item_default_location($oldbibitemnum);
335     }
336         $nextop = "additem";
337         if ($exist_itemnumber) {
338             $itemrecord = $record;
339         }
340     }
341
342     # If we have to add & duplicate
343     if ($add_duplicate_submit) {
344         $itemrecord = $record;
345         if (C4::Context->preference('autoBarcode') eq 'incremental') {
346             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
347         }
348         else {
349             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
350             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
351             my $fieldItem = $itemrecord->field($tagfield);
352             $itemrecord->delete_field($fieldItem);
353             $fieldItem->delete_subfields($tagsubfield);
354             $itemrecord->insert_fields_ordered($fieldItem);
355         }
356     }
357
358     # If we have to add multiple copies
359     if ($add_multiple_copies_submit) {
360
361         use C4::Barcodes;
362         my $barcodeobj = C4::Barcodes->new;
363         my $oldbarcode = $addedolditem->{'barcode'};
364         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
365
366         # If there is a barcode and we can't find him new values, we can't add multiple copies
367         my $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
368         if ($oldbarcode && !$testbarcode) {
369
370             push @errors, "no_next_barcode";
371             $itemrecord = $record;
372
373         } else {
374         # We add each item
375
376             # For the first iteration
377             my $barcodevalue = $oldbarcode;
378             my $exist_itemnumber;
379
380
381             for (my $i = 0; $i < $number_of_copies;) {
382
383                 # If there is a barcode
384                 if ($barcodevalue) {
385
386                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
387                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
388
389                     # Putting it into the record
390                     if ($barcodevalue) {
391                         $record->field($tagfield)->update($tagsubfield => $barcodevalue);
392                     }
393
394                     # Checking if the barcode already exists
395                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
396                 }
397
398                 # Adding the item
399         if (!$exist_itemnumber) {
400             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
401             set_item_default_location($oldbibitemnum);
402
403             # We count the item only if it was really added
404             # That way, all items are added, even if there was some already existing barcodes
405             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
406             $i++;
407         }
408
409                 # Preparing the next iteration
410                 $oldbarcode = $barcodevalue;
411             }
412             undef($itemrecord);
413         }
414     }
415
416
417 #-------------------------------------------------------------------------------
418 } elsif ($op eq "edititem") {
419 #-------------------------------------------------------------------------------
420 # retrieve item if exist => then, it's a modif
421     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
422     $nextop = "saveitem";
423 #-------------------------------------------------------------------------------
424 } elsif ($op eq "delitem") {
425 #-------------------------------------------------------------------------------
426     # check that there is no issue on this item before deletion.
427     $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
428     if($error == 1){
429         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
430     }else{
431         push @errors,$error;
432         $nextop="additem";
433     }
434 #-------------------------------------------------------------------------------
435 } elsif ($op eq "delallitems") {
436 #-------------------------------------------------------------------------------
437     my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
438     foreach my $biblioitem (@biblioitems){
439         my $items = &GetItemsByBiblioitemnumber($biblioitem->{biblioitemnumber});
440
441         foreach my $item (@$items){
442             # FIXME although it won't delete items that have loans
443             # or waiting holds on them, should explicitly tell operator
444             # about items that are not deleted
445             &DelItemCheck($dbh,$biblionumber,$item->{itemnumber});
446         }
447         }
448 #-------------------------------------------------------------------------------
449 } elsif ($op eq "saveitem") {
450 #-------------------------------------------------------------------------------
451     # rebuild
452     my @tags      = $input->param('tag');
453     my @subfields = $input->param('subfield');
454     my @values    = $input->param('field_value');
455     # build indicator hash.
456     my @ind_tag   = $input->param('ind_tag');
457     my @indicator = $input->param('indicator');
458     # my $itemnumber = $input->param('itemnumber');
459     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
460     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
461     # MARC::Record builded => now, record in DB
462     # warn "R: ".$record->as_formatted;
463     # check that the barcode don't exist already
464     my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
465     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
466     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
467         push @errors,"barcode_not_unique";
468     } else {
469         my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
470         $itemnumber="";
471     }
472     $nextop="additem";
473 }
474
475 #
476 #-------------------------------------------------------------------------------
477 # build screen with existing items. and "new" one
478 #-------------------------------------------------------------------------------
479
480 # now, build existiing item list
481 my $temp = GetMarcBiblio( $biblionumber );
482 my @fields = $temp->fields();
483 #my @fields = $record->fields();
484 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
485 my @big_array;
486 #---- finds where items.itemnumber is stored
487 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
488 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
489
490 foreach my $field (@fields) {
491     next if ( $field->tag() < 10 );
492
493     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
494     my %this_row;
495     # loop through each subfield
496     my $i = 0;
497     foreach my $subfield (@subf){
498         my $subfieldcode = $subfield->[0];
499         my $subfieldvalue= $subfield->[1];
500
501         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
502                 && ($field->tag() ne $itemtagfield 
503                 && $subfieldcode   ne $itemtagsubfield));
504         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
505                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
506                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
507                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
508                         $subfieldcode, $subfieldvalue, '', $tagslib) 
509                                                 || $subfieldvalue;
510         }
511
512         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
513             #verifying rights
514             my $userenv = C4::Context->userenv();
515             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subfieldvalue))){
516                 $this_row{'nomod'} = 1;
517             }
518         }
519         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
520     }
521     if (%this_row) {
522         push(@big_array, \%this_row);
523     }
524 }
525
526 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
527 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
528
529 # now, construct template !
530 # First, the existing items for display
531 my @item_value_loop;
532 my @header_value_loop;
533 for my $row ( @big_array ) {
534     my %row_data;
535     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
536     $row_data{item_value} = [ @item_fields ];
537     $row_data{itemnumber} = $row->{itemnumber};
538     #reporting this_row values
539     $row_data{'nomod'} = $row->{'nomod'};
540     push(@item_value_loop,\%row_data);
541 }
542 foreach my $subfield_code (sort keys(%witness)) {
543     my %header_value;
544     $header_value{header_value} = $witness{$subfield_code};
545     push(@header_value_loop, \%header_value);
546 }
547
548 # now, build the item form for entering a new item
549 my @loop_data =();
550 my $i=0;
551
552 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
553
554 my $onlymine = C4::Context->preference('IndependantBranches') && 
555                C4::Context->userenv                           && 
556                C4::Context->userenv->{flags}!=1               && 
557                C4::Context->userenv->{branch};
558 my $branches = GetBranchesLoop(undef,$onlymine);  # build once ahead of time, instead of multiple times later.
559
560 # We generate form, from actuel record
561 my @fields;
562 if($itemrecord){
563     foreach my $field ($itemrecord->fields()){
564         my $tag = $field->{_tag};
565         foreach my $subfield ( $field->subfields() ){
566
567             my $subfieldtag = $subfield->[0];
568             my $value       = $subfield->[1];
569             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
570
571             next if subfield_is_koha_internal_p($subfieldtag);
572             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
573
574             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);        
575
576             push @fields, "$tag$subfieldtag";
577             push (@loop_data, $subfield_data);
578             $i++;
579                     }
580
581                 }
582             }
583     # and now we add fields that are empty
584
585 foreach my $tag ( keys %{$tagslib}){
586     foreach my $subtag (keys %{$tagslib->{$tag}}){
587         next if subfield_is_koha_internal_p($subtag);
588         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
589         next if any { /^$tag$subtag$/ }  @fields;
590
591         my $value = "";
592         my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);
593
594         push (@loop_data, $subfield_data);
595         $i++;
596     }
597   }
598 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
599 $template->param( title => $record->title() ) if ($record ne "-1");
600 $template->param(
601     biblionumber => $biblionumber,
602     title        => $oldrecord->{title},
603     author       => $oldrecord->{author},
604     item_loop        => \@item_value_loop,
605     item_header_loop => \@header_value_loop,
606     item             => \@loop_data,
607     itemnumber       => $itemnumber,
608     itemtagfield     => $itemtagfield,
609     itemtagsubfield  => $itemtagsubfield,
610     op      => $nextop,
611     opisadd => ($nextop eq "saveitem") ? 0 : 1,
612     C4::Search::enabled_staff_search_views,
613 );
614 foreach my $error (@errors) {
615     $template->param($error => 1);
616 }
617 output_html_with_http_headers $input, $cookie, $template->output;