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