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