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