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