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