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