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