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