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