Bug 18254: Remove call to GetItemsByBiblioitemnumber call from additem.pl
[koha-equinox.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
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use CGI qw ( -utf8 );
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Context;
30 use C4::Circulation;
31 use C4::Koha;
32 use C4::ClassSource;
33 use Koha::DateUtils;
34 use Koha::ItemTypes;
35 use Koha::Libraries;
36 use List::MoreUtils qw/any/;
37 use C4::Search;
38 use Storable qw(thaw freeze);
39 use URI::Escape;
40 use C4::Members;
41
42 use MARC::File::XML;
43 use URI::Escape;
44
45 our $dbh = C4::Context->dbh;
46
47 sub find_value {
48     my ($tagfield,$insubfield,$record) = @_;
49     my $result;
50     my $indicator;
51     foreach my $field ($record->field($tagfield)) {
52         my @subfields = $field->subfields();
53         foreach my $subfield (@subfields) {
54             if (@$subfield[0] eq $insubfield) {
55                 $result .= @$subfield[1];
56                 $indicator = $field->indicator(1).$field->indicator(2);
57             }
58         }
59     }
60     return($indicator,$result);
61 }
62
63 sub get_item_from_barcode {
64     my ($barcode)=@_;
65     my $dbh=C4::Context->dbh;
66     my $result;
67     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
68     $rq->execute($barcode);
69     ($result)=$rq->fetchrow;
70     return($result);
71 }
72
73 sub set_item_default_location {
74     my $itemnumber = shift;
75     my $item = GetItem( $itemnumber );
76     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
77         $item->{'permanent_location'} = $item->{'location'};
78         $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
79         ModItem( $item, undef, $itemnumber);
80     }
81     else {
82       $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
83       ModItem( $item, undef, $itemnumber);
84     }
85 }
86
87 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
88 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
89 sub _increment_barcode {
90     my ($record, $frameworkcode) = @_;
91     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
92     unless ($record->field($tagfield)->subfield($tagsubfield)) {
93         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
94         $sth_barcode->execute;
95         my ($newbarcode) = $sth_barcode->fetchrow;
96         $newbarcode++;
97         # OK, we have the new barcode, now create the entry in MARC record
98         my $fieldItem = $record->field($tagfield);
99         $record->delete_field($fieldItem);
100         $fieldItem->add_subfields($tagsubfield => $newbarcode);
101         $record->insert_fields_ordered($fieldItem);
102     }
103     return $record;
104 }
105
106
107 sub generate_subfield_form {
108         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
109   
110         my $frameworkcode = &GetFrameworkCode($biblionumber);
111
112         my %subfield_data;
113         my $dbh = C4::Context->dbh;
114         
115         my $index_subfield = int(rand(1000000)); 
116         if ($subfieldtag eq '@'){
117             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
118         } else {
119             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
120         }
121         
122         $subfield_data{tag}        = $tag;
123         $subfield_data{subfield}   = $subfieldtag;
124         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
125         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
126         $subfield_data{repeatable} = $subfieldlib->{repeatable};
127         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
128         
129         $value =~ s/"/&quot;/g;
130         if ( ! defined( $value ) || $value eq '')  {
131             $value = $subfieldlib->{defaultvalue};
132             # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
133             my $today_dt = dt_from_string;
134             my $year = $today_dt->strftime('%Y');
135             my $month = $today_dt->strftime('%m');
136             my $day = $today_dt->strftime('%d');
137             $value =~ s/<<YYYY>>/$year/g;
138             $value =~ s/<<MM>>/$month/g;
139             $value =~ s/<<DD>>/$day/g;
140             # And <<USER>> with surname (?)
141             my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
142             $value=~s/<<USER>>/$username/g;
143         }
144         
145         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
146         
147         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
148         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
149             my $CNtag       = substr($pref_itemcallnumber, 0, 3);
150             my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
151             my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
152             my $temp2 = $temp->field($CNtag);
153             if ($temp2) {
154                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
155                 #remove any trailing space incase one subfield is used
156                 $value =~ s/^\s+|\s+$//g;
157             }
158         }
159         
160         if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
161             my $input = new CGI;
162             $value = $input->param('barcode');
163         }
164
165         # Getting list of subfields to keep when restricted editing is enabled
166         my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
167         my $allowAllSubfields = (
168             not defined $subfieldsToAllowForRestrictedEditing
169               or $subfieldsToAllowForRestrictedEditing == q||
170         ) ? 1 : 0;
171         my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
172
173         if ( $subfieldlib->{authorised_value} ) {
174             my @authorised_values;
175             my %authorised_lib;
176             # builds list, depending on authorised value...
177             if ( $subfieldlib->{authorised_value} eq "branches" ) {
178                 foreach my $thisbranch (@$branches) {
179                     push @authorised_values, $thisbranch->{branchcode};
180                     $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
181                     $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
182                 }
183             }
184             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
185                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
186                   my $itemtypes = Koha::ItemTypes->search_with_localization;
187                   while ( my $itemtype = $itemtypes->next ) {
188                       push @authorised_values, $itemtype->itemtype;
189                       $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
190                   }
191
192                   unless ( $value ) {
193                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
194                       $itype_sth->execute( $biblionumber );
195                       ( $value ) = $itype_sth->fetchrow_array;
196                   }
197           
198                   #---- class_sources
199             }
200             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
201                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
202                     
203                   my $class_sources = GetClassSources();
204                   my $default_source = C4::Context->preference("DefaultClassificationSource");
205                   
206                   foreach my $class_source (sort keys %$class_sources) {
207                       next unless $class_sources->{$class_source}->{'used'} or
208                                   ($value and $class_source eq $value)      or
209                                   ($class_source eq $default_source);
210                       push @authorised_values, $class_source;
211                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
212                   }
213                           $value = $default_source unless ($value);
214         
215                   #---- "true" authorised value
216             }
217             else {
218                   push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
219                   my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
220                   for my $r ( @$av ) {
221                       push @authorised_values, $r->{authorised_value};
222                       $authorised_lib{$r->{authorised_value}} = $r->{lib};
223                   }
224             }
225
226             if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
227                 $subfield_data{marc_value} = {
228                     type        => 'hidden',
229                     id          => $subfield_data{id},
230                     maxlength   => $subfield_data{max_length},
231                     value       => $value,
232                 };
233             }
234             else {
235                 $subfield_data{marc_value} = {
236                     type     => 'select',
237                     id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
238                     values   => \@authorised_values,
239                     labels   => \%authorised_lib,
240                     default  => $value,
241                 };
242                 # If we're on restricted editing, and our field is not in the list of subfields to allow,
243                 # then it is read-only
244                 $subfield_data{marc_value}->{readonlyselect} = (
245                     not $allowAllSubfields
246                     and $restrictededition
247                     and !grep { $tag . '$' . $subfieldtag  eq $_ } @subfieldsToAllow
248                 ) ? 1: 0;
249             }
250         }
251             # it's a thesaurus / authority field
252         elsif ( $subfieldlib->{authtypecode} ) {
253                 $subfield_data{marc_value} = {
254                     type         => 'text_auth',
255                     id           => $subfield_data{id},
256                     maxlength    => $subfield_data{max_length},
257                     value        => $value,
258                     authtypecode => $subfieldlib->{authtypecode},
259                 };
260         }
261             # it's a plugin field
262         elsif ( $subfieldlib->{value_builder} ) { # plugin
263             require Koha::FrameworkPlugin;
264             my $plugin = Koha::FrameworkPlugin->new({
265                 name => $subfieldlib->{'value_builder'},
266                 item_style => 1,
267             });
268             my $pars=  { dbh => $dbh, record => $temp, tagslib =>$tagslib,
269                 id => $subfield_data{id}, tabloop => $loop_data };
270             $plugin->build( $pars );
271             if( !$plugin->errstr ) {
272                 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
273                 $subfield_data{marc_value} = {
274                     type        => 'text_plugin',
275                     id          => $subfield_data{id},
276                     maxlength   => $subfield_data{max_length},
277                     value       => $value,
278                     class       => $class,
279                     nopopup     => $plugin->noclick,
280                     javascript  => $plugin->javascript,
281                 };
282             } else {
283                 warn $plugin->errstr;
284                 $subfield_data{marc_value} = {
285                     type        => 'text',
286                     id          => $subfield_data{id},
287                     maxlength   => $subfield_data{max_length},
288                     value       => $value,
289                 }; # supply default input form
290             }
291         }
292         elsif ( $tag eq '' ) {       # it's an hidden field
293             $subfield_data{marc_value} = {
294                 type        => 'hidden',
295                 id          => $subfield_data{id},
296                 maxlength   => $subfield_data{max_length},
297                 value       => $value,
298             };
299         }
300         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
301             $subfield_data{marc_value} = {
302                 type        => 'text',
303                 id          => $subfield_data{id},
304                 maxlength   => $subfield_data{max_length},
305                 value       => $value,
306             };
307         }
308         elsif (
309                 length($value) > 100
310                 or (
311                     C4::Context->preference("marcflavour") eq "UNIMARC"
312                     and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
313                 )
314                 or (
315                     C4::Context->preference("marcflavour") eq "MARC21"
316                     and 500 <= $tag && $tag < 600
317                 )
318               ) {
319             # oversize field (textarea)
320             $subfield_data{marc_value} = {
321                 type        => 'textarea',
322                 id          => $subfield_data{id},
323                 value       => $value,
324             };
325         } else {
326             # it's a standard field
327             $subfield_data{marc_value} = {
328                 type        => 'text',
329                 id          => $subfield_data{id},
330                 maxlength   => $subfield_data{max_length},
331                 value       => $value,
332             };
333         }
334         
335         return \%subfield_data;
336 }
337
338 # Removes some subfields when prefilling items
339 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
340 sub removeFieldsForPrefill {
341
342     my $item = shift;
343
344     # Getting item tag
345     my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
346
347     # Getting list of subfields to keep
348     my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
349
350     # Removing subfields that are not in the syspref
351     if ($tag && $subfieldsToUseWhenPrefill) {
352         my $field = $item->field($tag);
353         my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
354         foreach my $subfield ($field->subfields()) {
355             if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
356                 $field->delete_subfield(code => $subfield->[0]);
357             }
358
359         }
360     }
361
362     return $item;
363
364 }
365
366 my $input        = new CGI;
367 my $error        = $input->param('error');
368 my $biblionumber = $input->param('biblionumber');
369 my $itemnumber   = $input->param('itemnumber');
370 my $op           = $input->param('op');
371 my $hostitemnumber = $input->param('hostitemnumber');
372 my $marcflavour  = C4::Context->preference("marcflavour");
373 my $searchid     = $input->param('searchid');
374 # fast cataloguing datas
375 my $fa_circborrowernumber = $input->param('circborrowernumber');
376 my $fa_barcode            = $input->param('barcode');
377 my $fa_branch             = $input->param('branch');
378 my $fa_stickyduedate      = $input->param('stickyduedate');
379 my $fa_duedatespec        = $input->param('duedatespec');
380
381 my $frameworkcode = &GetFrameworkCode($biblionumber);
382
383 # Defining which userflag is needing according to the framework currently used
384 my $userflags;
385 if (defined $input->param('frameworkcode')) {
386     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
387 }
388
389 if (not defined $userflags) {
390     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
391 }
392
393 my ($template, $loggedinuser, $cookie)
394     = get_template_and_user({template_name => "cataloguing/additem.tt",
395                  query => $input,
396                  type => "intranet",
397                  authnotrequired => 0,
398                  flagsrequired => {editcatalogue => $userflags},
399                  debug => 1,
400                  });
401
402
403 # Does the user have a restricted item editing permission?
404 my $uid = $loggedinuser ? GetMember( borrowernumber => $loggedinuser )->{userid} : undef;
405 my $restrictededition = $uid ? haspermission($uid,  {'editcatalogue' => 'edit_items_restricted'}) : undef;
406 # In case user is a superlibrarian, editing is not restricted
407 $restrictededition = 0 if ($restrictededition != 0 &&  C4::Context->IsSuperLibrarian());
408 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
409 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
410
411 my $tagslib = &GetMarcStructure(1,$frameworkcode);
412 my $record = GetMarcBiblio($biblionumber);
413 my $oldrecord = TransformMarcToKoha($record);
414 my $itemrecord;
415 my $nextop="additem";
416 my @errors; # store errors found while checking data BEFORE saving item.
417
418 # Getting last created item cookie
419 my $prefillitem = C4::Context->preference('PrefillItem');
420 my $justaddeditem;
421 my $cookieitemrecord;
422 if ($prefillitem) {
423     my $lastitemcookie = $input->cookie('LastCreatedItem');
424     if ($lastitemcookie) {
425         $lastitemcookie = uri_unescape($lastitemcookie);
426         eval {
427             if ( thaw($lastitemcookie) ) {
428                 $cookieitemrecord = thaw($lastitemcookie);
429                 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
430             }
431         };
432         if ($@) {
433             $lastitemcookie = 'undef' unless $lastitemcookie;
434             warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
435         }
436     }
437 }
438
439 #-------------------------------------------------------------------------------
440 if ($op eq "additem") {
441
442     #-------------------------------------------------------------------------------
443     # rebuild
444     my @tags      = $input->multi_param('tag');
445     my @subfields = $input->multi_param('subfield');
446     my @values    = $input->multi_param('field_value');
447     # build indicator hash.
448     my @ind_tag   = $input->multi_param('ind_tag');
449     my @indicator = $input->multi_param('indicator');
450     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
451     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
452
453     # type of add
454     my $add_submit                 = $input->param('add_submit');
455     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
456     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
457     my $number_of_copies           = $input->param('number_of_copies');
458
459     # This is a bit tricky : if there is a cookie for the last created item and
460     # we just added an item, the cookie value is not correct yet (it will be updated
461     # next page). To prevent the form from being filled with outdated values, we
462     # force the use of "add and duplicate" feature, so the form will be filled with
463     # correct values.
464     $add_duplicate_submit = 1 if ($prefillitem);
465     $justaddeditem = 1;
466
467     # if autoBarcode is set to 'incremental', calculate barcode...
468     if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
469         $record = _increment_barcode($record, $frameworkcode);
470     }
471
472     my $addedolditem = TransformMarcToKoha( $record );
473
474     # If we have to add or add & duplicate, we add the item
475     if ( $add_submit || $add_duplicate_submit ) {
476
477         # check for item barcode # being unique
478         my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
479         push @errors, "barcode_not_unique" if ($exist_itemnumber);
480
481         # if barcode exists, don't create, but report The problem.
482         unless ($exist_itemnumber) {
483             my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
484             set_item_default_location($oldbibitemnum);
485
486             # Pushing the last created item cookie back
487             if ($prefillitem && defined $record) {
488                 my $itemcookie = $input->cookie(
489                     -name => 'LastCreatedItem',
490                     # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
491                     -value   => uri_escape_utf8( freeze( $record ) ),
492                     -HttpOnly => 1,
493                     -expires => ''
494                 );
495
496                 $cookie = [ $cookie, $itemcookie ];
497             }
498
499         }
500         $nextop = "additem";
501         if ($exist_itemnumber) {
502             $itemrecord = $record;
503         }
504     }
505
506     # If we have to add & duplicate
507     if ($add_duplicate_submit) {
508         $itemrecord = $record;
509         if (C4::Context->preference('autoBarcode') eq 'incremental') {
510             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
511         }
512         else {
513             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
514             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
515             my $fieldItem = $itemrecord->field($tagfield);
516             $itemrecord->delete_field($fieldItem);
517             $fieldItem->delete_subfields($tagsubfield);
518             $itemrecord->insert_fields_ordered($fieldItem);
519         }
520     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
521     }
522
523     # If we have to add multiple copies
524     if ($add_multiple_copies_submit) {
525
526         use C4::Barcodes;
527         my $barcodeobj = C4::Barcodes->new;
528         my $oldbarcode = $addedolditem->{'barcode'};
529         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
530
531     # If there is a barcode and we can't find their new values, we can't add multiple copies
532         my $testbarcode;
533         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
534         if ($oldbarcode && !$testbarcode) {
535
536             push @errors, "no_next_barcode";
537             $itemrecord = $record;
538
539         } else {
540         # We add each item
541
542             # For the first iteration
543             my $barcodevalue = $oldbarcode;
544             my $exist_itemnumber;
545
546
547             for (my $i = 0; $i < $number_of_copies;) {
548
549                 # If there is a barcode
550                 if ($barcodevalue) {
551
552                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
553                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
554
555                     # Putting it into the record
556                     if ($barcodevalue) {
557                         $record->field($tagfield)->update($tagsubfield => $barcodevalue);
558                     }
559
560                     # Checking if the barcode already exists
561                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
562                 }
563
564                 # Adding the item
565         if (!$exist_itemnumber) {
566             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
567             set_item_default_location($oldbibitemnum);
568
569             # We count the item only if it was really added
570             # That way, all items are added, even if there was some already existing barcodes
571             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
572             $i++;
573         }
574
575                 # Preparing the next iteration
576                 $oldbarcode = $barcodevalue;
577             }
578             undef($itemrecord);
579         }
580     }   
581     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
582         print $input->redirect(
583            '/cgi-bin/koha/circ/circulation.pl?'
584            .'borrowernumber='.$fa_circborrowernumber
585            .'&barcode='.uri_escape_utf8($fa_barcode)
586            .'&duedatespec='.$fa_duedatespec
587            .'&stickyduedate=1'
588         );
589         exit;
590     }
591
592
593 #-------------------------------------------------------------------------------
594 } elsif ($op eq "edititem") {
595 #-------------------------------------------------------------------------------
596 # retrieve item if exist => then, it's a modif
597     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
598     $nextop = "saveitem";
599 #-------------------------------------------------------------------------------
600 } elsif ($op eq "dupeitem") {
601 #-------------------------------------------------------------------------------
602 # retrieve item if exist => then, it's a modif
603     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
604     if (C4::Context->preference('autoBarcode') eq 'incremental') {
605         $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
606     }
607     else {
608         # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
609         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
610         my $fieldItem = $itemrecord->field($tagfield);
611         $itemrecord->delete_field($fieldItem);
612         $fieldItem->delete_subfields($tagsubfield);
613         $itemrecord->insert_fields_ordered($fieldItem);
614     }
615
616     #check for hidden subfield and remove them for the duplicated item
617     foreach my $field ($itemrecord->fields()){
618         my $tag = $field->{_tag};
619         foreach my $subfield ($field->subfields()){
620             my $subfieldtag = $subfield->[0];
621             if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
622             ||  abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
623                 my $fieldItem = $itemrecord->field($tag);
624                 $itemrecord->delete_field($fieldItem);
625                 $fieldItem->delete_subfields($subfieldtag);
626                 $itemrecord->insert_fields_ordered($fieldItem);
627             }
628         }
629     }
630
631     $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
632     $nextop = "additem";
633 #-------------------------------------------------------------------------------
634 } elsif ($op eq "delitem") {
635 #-------------------------------------------------------------------------------
636     # check that there is no issue on this item before deletion.
637     $error = &DelItemCheck( $biblionumber,$itemnumber);
638     if($error == 1){
639         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
640     }else{
641         push @errors,$error;
642         $nextop="additem";
643     }
644 #-------------------------------------------------------------------------------
645 } elsif ($op eq "delallitems") {
646 #-------------------------------------------------------------------------------
647     my $itemnumbers = C4::Items::GetItemnumbersForBiblio( $biblionumber );
648     foreach my $itemnumber ( @$itemnumbers ) {
649         $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
650         next if $error == 1; # Means ok
651         push @errors,$error;
652     }
653     if ( @errors ) {
654         $nextop="additem";
655     } else {
656         my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
657         my $views = { C4::Search::enabled_staff_search_views };
658         if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
659             print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
660         } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
661             print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
662         } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
663             print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
664         } else {
665             print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
666         }
667         exit;
668     }
669 #-------------------------------------------------------------------------------
670 } elsif ($op eq "saveitem") {
671 #-------------------------------------------------------------------------------
672     # rebuild
673     my @tags      = $input->multi_param('tag');
674     my @subfields = $input->multi_param('subfield');
675     my @values    = $input->multi_param('field_value');
676     # build indicator hash.
677     my @ind_tag   = $input->multi_param('ind_tag');
678     my @indicator = $input->multi_param('indicator');
679     # my $itemnumber = $input->param('itemnumber');
680     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
681     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
682     # MARC::Record builded => now, record in DB
683     # warn "R: ".$record->as_formatted;
684     # check that the barcode don't exist already
685     my $addedolditem = TransformMarcToKoha($itemtosave);
686     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
687     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
688         push @errors,"barcode_not_unique";
689     } else {
690         ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
691         $itemnumber="";
692     }
693   my $item = GetItem( $itemnumber );
694     my $olditemlost =  $item->{'itemlost'};
695
696    my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
697
698    my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
699     if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
700   LostItem($itemnumber,'MARK RETURNED');
701     }
702     $nextop="additem";
703 } elsif ($op eq "delinkitem"){
704     my $analyticfield = '773';
705         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
706         $analyticfield = '773';
707     } elsif ($marcflavour eq 'UNIMARC') {
708         $analyticfield = '461';
709     }
710     foreach my $field ($record->field($analyticfield)){
711         if ($field->subfield('9') eq $hostitemnumber){
712             $record->delete_field($field);
713             last;
714         }
715     }
716         my $modbibresult = ModBiblio($record, $biblionumber,'');
717 }
718
719 #
720 #-------------------------------------------------------------------------------
721 # build screen with existing items. and "new" one
722 #-------------------------------------------------------------------------------
723
724 # now, build existiing item list
725 my $temp = GetMarcBiblio( $biblionumber );
726 #my @fields = $record->fields();
727
728
729 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
730 my @big_array;
731 #---- finds where items.itemnumber is stored
732 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
733 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
734 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
735 my @fields = $temp->fields();
736
737
738 my @hostitemnumbers;
739 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
740     my $analyticfield = '773';
741     if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC') {
742         $analyticfield = '773';
743     } elsif ($marcflavour eq 'UNIMARC') {
744         $analyticfield = '461';
745     }
746     foreach my $hostfield ($temp->field($analyticfield)){
747         my $hostbiblionumber = $hostfield->subfield('0');
748         if ($hostbiblionumber){
749             my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
750             if ($hostrecord) {
751                 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
752                 foreach my $hostitem ($hostrecord->field($itemfield)){
753                     if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
754                         push (@fields, $hostitem);
755                         push (@hostitemnumbers, $hostfield->subfield('9'));
756                     }
757                 }
758             }
759         }
760     }
761 }
762
763
764 foreach my $field (@fields) {
765     next if ( $field->tag() < 10 );
766
767     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
768     my %this_row;
769     # loop through each subfield
770     my $i = 0;
771     foreach my $subfield (@subf){
772         my $subfieldcode = $subfield->[0];
773         my $subfieldvalue= $subfield->[1];
774
775         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
776                 && ($field->tag() ne $itemtagfield 
777                 && $subfieldcode   ne $itemtagsubfield));
778         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
779                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
780                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
781                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
782                         $subfieldcode, $subfieldvalue, '', $tagslib) 
783                                                 || $subfieldvalue;
784         }
785
786         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
787             #verifying rights
788             my $userenv = C4::Context->userenv();
789             unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
790                 $this_row{'nomod'} = 1;
791             }
792         }
793         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
794
795         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
796             foreach my $hostitemnumber (@hostitemnumbers){
797                 if ($this_row{itemnumber} eq $hostitemnumber){
798                         $this_row{hostitemflag} = 1;
799                         $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
800                         last;
801                 }
802             }
803
804 #           my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
805 #           if ($countanalytics > 0){
806 #                $this_row{countanalytics} = $countanalytics;
807 #           }
808         }
809
810     }
811     if (%this_row) {
812         push(@big_array, \%this_row);
813     }
814 }
815
816 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
817 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
818
819 # now, construct template !
820 # First, the existing items for display
821 my @item_value_loop;
822 my @header_value_loop;
823 for my $row ( @big_array ) {
824     my %row_data;
825     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
826     $row_data{item_value} = [ @item_fields ];
827     $row_data{itemnumber} = $row->{itemnumber};
828     #reporting this_row values
829     $row_data{'nomod'} = $row->{'nomod'};
830     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
831     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
832 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
833     push(@item_value_loop,\%row_data);
834 }
835 foreach my $subfield_code (sort keys(%witness)) {
836     my %header_value;
837     $header_value{header_value} = $witness{$subfield_code};
838
839     my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
840     my $kohafield = $subfieldlib->{kohafield};
841     if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
842         $header_value{column_name} = $1;
843     }
844
845     push(@header_value_loop, \%header_value);
846 }
847
848 # now, build the item form for entering a new item
849 my @loop_data =();
850 my $i=0;
851
852 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
853
854 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
855 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
856 for my $library ( @$libraries ) {
857     $library->{selected} = 1 if $library->{branchcode} eq $branch
858 }
859
860 # We generate form, from actuel record
861 @fields = ();
862 if($itemrecord){
863     foreach my $field ($itemrecord->fields()){
864         my $tag = $field->{_tag};
865         foreach my $subfield ( $field->subfields() ){
866
867             my $subfieldtag = $subfield->[0];
868             my $value       = $subfield->[1];
869             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
870
871             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
872
873             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
874             push @fields, "$tag$subfieldtag";
875             push (@loop_data, $subfield_data);
876             $i++;
877                     }
878
879                 }
880             }
881     # and now we add fields that are empty
882
883 # Using last created item if it exists
884
885 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
886
887 # We generate form, and fill with values if defined
888 foreach my $tag ( keys %{$tagslib}){
889     foreach my $subtag (keys %{$tagslib->{$tag}}){
890         next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
891         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
892         next if any { /^$tag$subtag$/ }  @fields;
893
894         my @values = (undef);
895         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
896         for my $value (@values){
897             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
898             push (@loop_data, $subfield_data);
899             $i++;
900         }
901   }
902 }
903 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
904
905 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
906 $template->param(
907     biblionumber => $biblionumber,
908     title        => $oldrecord->{title},
909     author       => $oldrecord->{author},
910     item_loop        => \@item_value_loop,
911     item_header_loop => \@header_value_loop,
912     item             => \@loop_data,
913     itemnumber       => $itemnumber,
914     barcode          => GetBarcodeFromItemnumber($itemnumber),
915     itemtagfield     => $itemtagfield,
916     itemtagsubfield  => $itemtagsubfield,
917     op      => $nextop,
918     opisadd => ($nextop eq "saveitem") ? 0 : 1,
919     popup => scalar $input->param('popup') ? 1: 0,
920     C4::Search::enabled_staff_search_views,
921 );
922 $template->{'VARS'}->{'searchid'} = $searchid;
923
924 if ($frameworkcode eq 'FA'){
925     # fast cataloguing datas
926     $template->param(
927         'circborrowernumber' => $fa_circborrowernumber,
928         'barcode'            => $fa_barcode,
929         'branch'             => $fa_branch,
930         'stickyduedate'      => $fa_stickyduedate,
931         'duedatespec'        => $fa_duedatespec,
932     );
933 }
934
935 foreach my $error (@errors) {
936     $template->param($error => 1);
937 }
938 output_html_with_http_headers $input, $cookie, $template->output;