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