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