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