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