[19.11.x] Bug 25858: Don't attempt to set flag if already set
[koha.git] / cataloguing / additem.pl
blob3b5f2b7ef00de2dd175597e9c5884cc950ee9a65
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
7 # This file is part of Koha.
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.
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.
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>.
22 use Modern::Perl;
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;
44 use MARC::File::XML;
45 use URI::Escape;
47 our $dbh = C4::Context->dbh;
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);
62 return($indicator,$result);
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);
75 sub set_item_default_location {
76 my $itemnumber = shift;
77 my $item = Koha::Items->find($itemnumber);
78 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
79 ModItem(
81 permanent_location => $item->location,
82 location => C4::Context->preference('NewItemsDefaultLocation')
84 undef,
85 $itemnumber
88 else {
89 ModItem( { permanent_location => $item->location }, undef, $itemnumber )
90 unless defined $item->permanent_location;
94 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
95 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
96 sub _increment_barcode {
97 my ($record, $frameworkcode) = @_;
98 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
99 unless ($record->field($tagfield)->subfield($tagsubfield)) {
100 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
101 $sth_barcode->execute;
102 my ($newbarcode) = $sth_barcode->fetchrow;
103 $newbarcode++;
104 # OK, we have the new barcode, now create the entry in MARC record
105 my $fieldItem = $record->field($tagfield);
106 $record->delete_field($fieldItem);
107 $fieldItem->add_subfields($tagsubfield => $newbarcode);
108 $record->insert_fields_ordered($fieldItem);
110 return $record;
114 sub generate_subfield_form {
115 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
117 my $frameworkcode = &GetFrameworkCode($biblionumber);
119 my %subfield_data;
120 my $dbh = C4::Context->dbh;
122 my $index_subfield = int(rand(1000000));
123 if ($subfieldtag eq '@'){
124 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
125 } else {
126 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
129 $subfield_data{tag} = $tag;
130 $subfield_data{subfield} = $subfieldtag;
131 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
132 $subfield_data{mandatory} = $subfieldlib->{mandatory};
133 $subfield_data{repeatable} = $subfieldlib->{repeatable};
134 $subfield_data{maxlength} = $subfieldlib->{maxlength};
136 if ( ! defined( $value ) || $value eq '') {
137 $value = $subfieldlib->{defaultvalue};
138 if ( $value ) {
139 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
140 my $today_dt = dt_from_string;
141 my $year = $today_dt->strftime('%Y');
142 my $month = $today_dt->strftime('%m');
143 my $day = $today_dt->strftime('%d');
144 $value =~ s/<<YYYY>>/$year/g;
145 $value =~ s/<<MM>>/$month/g;
146 $value =~ s/<<DD>>/$day/g;
147 # And <<USER>> with surname (?)
148 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
149 $value=~s/<<USER>>/$username/g;
153 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
155 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
156 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
157 my $CNtag = substr( $pref_itemcallnumber, 0, 3 ); # 3-digit tag number
158 my $CNsubfields = substr( $pref_itemcallnumber, 3 ); # Any and all subfields
159 my $temp2 = $temp->field($CNtag);
161 if ($temp2) {
162 $value = $temp2->as_string( $CNsubfields, ' ' );
166 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
167 my $input = new CGI;
168 $value = $input->param('barcode');
171 if ( $subfieldlib->{authorised_value} ) {
172 my @authorised_values;
173 my %authorised_lib;
174 # builds list, depending on authorised value...
175 if ( $subfieldlib->{authorised_value} eq "branches" ) {
176 foreach my $thisbranch (@$branches) {
177 push @authorised_values, $thisbranch->{branchcode};
178 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
179 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
182 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
183 push @authorised_values, "";
184 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
185 my $itemtypes;
186 if($branch_limit) {
187 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
188 } else {
189 $itemtypes = Koha::ItemTypes->search_with_localization;
191 while ( my $itemtype = $itemtypes->next ) {
192 push @authorised_values, $itemtype->itemtype;
193 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
196 unless ( $value ) {
197 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
198 $itype_sth->execute( $biblionumber );
199 ( $value ) = $itype_sth->fetchrow_array;
202 #---- class_sources
204 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
205 push @authorised_values, "";
207 my $class_sources = GetClassSources();
208 my $default_source = C4::Context->preference("DefaultClassificationSource");
210 foreach my $class_source (sort keys %$class_sources) {
211 next unless $class_sources->{$class_source}->{'used'} or
212 ($value and $class_source eq $value) or
213 ($class_source eq $default_source);
214 push @authorised_values, $class_source;
215 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
217 $value = $default_source unless ($value);
219 #---- "true" authorised value
221 else {
222 push @authorised_values, qq{};
223 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
224 for my $r ( @$av ) {
225 push @authorised_values, $r->{authorised_value};
226 $authorised_lib{$r->{authorised_value}} = $r->{lib};
230 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
231 $subfield_data{marc_value} = {
232 type => 'hidden',
233 id => $subfield_data{id},
234 maxlength => $subfield_data{maxlength},
235 value => $value,
238 else {
239 $subfield_data{marc_value} = {
240 type => 'select',
241 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
242 values => \@authorised_values,
243 labels => \%authorised_lib,
244 default => $value,
248 # it's a thesaurus / authority field
249 elsif ( $subfieldlib->{authtypecode} ) {
250 $subfield_data{marc_value} = {
251 type => 'text_auth',
252 id => $subfield_data{id},
253 maxlength => $subfield_data{maxlength},
254 value => $value,
255 authtypecode => $subfieldlib->{authtypecode},
258 # it's a plugin field
259 elsif ( $subfieldlib->{value_builder} ) { # plugin
260 require Koha::FrameworkPlugin;
261 my $plugin = Koha::FrameworkPlugin->new({
262 name => $subfieldlib->{'value_builder'},
263 item_style => 1,
265 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
266 id => $subfield_data{id}, tabloop => $loop_data };
267 $plugin->build( $pars );
268 if( !$plugin->errstr ) {
269 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
270 $subfield_data{marc_value} = {
271 type => 'text_plugin',
272 id => $subfield_data{id},
273 maxlength => $subfield_data{maxlength},
274 value => $value,
275 class => $class,
276 nopopup => $plugin->noclick,
277 javascript => $plugin->javascript,
279 } else {
280 warn $plugin->errstr;
281 $subfield_data{marc_value} = {
282 type => 'text',
283 id => $subfield_data{id},
284 maxlength => $subfield_data{maxlength},
285 value => $value,
286 }; # supply default input form
289 elsif ( $tag eq '' ) { # it's an hidden field
290 $subfield_data{marc_value} = {
291 type => 'hidden',
292 id => $subfield_data{id},
293 maxlength => $subfield_data{maxlength},
294 value => $value,
297 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
298 $subfield_data{marc_value} = {
299 type => 'text',
300 id => $subfield_data{id},
301 maxlength => $subfield_data{maxlength},
302 value => $value,
305 elsif (
307 $value and length($value) > 100
309 or (
310 C4::Context->preference("marcflavour") eq "UNIMARC"
311 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
313 or (
314 C4::Context->preference("marcflavour") eq "MARC21"
315 and 500 <= $tag && $tag < 600
318 # oversize field (textarea)
319 $subfield_data{marc_value} = {
320 type => 'textarea',
321 id => $subfield_data{id},
322 value => $value,
324 } else {
325 # it's a standard field
326 $subfield_data{marc_value} = {
327 type => 'text',
328 id => $subfield_data{id},
329 maxlength => $subfield_data{maxlength},
330 value => $value,
334 # Getting list of subfields to keep when restricted editing is enabled
335 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
336 my $allowAllSubfields = (
337 not defined $subfieldsToAllowForRestrictedEditing
338 or $subfieldsToAllowForRestrictedEditing eq q||
339 ) ? 1 : 0;
340 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
342 # If we're on restricted editing, and our field is not in the list of subfields to allow,
343 # then it is read-only
344 $subfield_data{marc_value}->{readonly} = (
345 not $allowAllSubfields
346 and $restrictededition
347 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
348 ) ? 1: 0;
350 return \%subfield_data;
353 # Removes some subfields when prefilling items
354 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
355 sub removeFieldsForPrefill {
357 my $item = shift;
359 # Getting item tag
360 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
362 # Getting list of subfields to keep
363 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
365 # Removing subfields that are not in the syspref
366 if ($tag && $subfieldsToUseWhenPrefill) {
367 my $field = $item->field($tag);
368 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
369 foreach my $subfield ($field->subfields()) {
370 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
371 $field->delete_subfield(code => $subfield->[0]);
377 return $item;
381 my $input = new CGI;
382 my $error = $input->param('error');
383 my $biblionumber = $input->param('biblionumber');
384 my $itemnumber = $input->param('itemnumber');
385 my $op = $input->param('op') || q{};
386 my $hostitemnumber = $input->param('hostitemnumber');
387 my $marcflavour = C4::Context->preference("marcflavour");
388 my $searchid = $input->param('searchid');
389 # fast cataloguing datas
390 my $fa_circborrowernumber = $input->param('circborrowernumber');
391 my $fa_barcode = $input->param('barcode');
392 my $fa_branch = $input->param('branch');
393 my $fa_stickyduedate = $input->param('stickyduedate');
394 my $fa_duedatespec = $input->param('duedatespec');
396 my $frameworkcode = &GetFrameworkCode($biblionumber);
398 # Defining which userflag is needing according to the framework currently used
399 my $userflags;
400 if (defined $input->param('frameworkcode')) {
401 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
404 if (not defined $userflags) {
405 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
408 my ($template, $loggedinuser, $cookie)
409 = get_template_and_user({template_name => "cataloguing/additem.tt",
410 query => $input,
411 type => "intranet",
412 authnotrequired => 0,
413 flagsrequired => {editcatalogue => $userflags},
414 debug => 1,
418 # Does the user have a restricted item editing permission?
419 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
420 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
421 # In case user is a superlibrarian, editing is not restricted
422 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
423 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
424 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
426 my $tagslib = &GetMarcStructure(1,$frameworkcode);
427 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
429 output_and_exit_if_error( $input, $cookie, $template,
430 { module => 'cataloguing', record => $record } );
432 my $oldrecord = TransformMarcToKoha($record);
433 my $itemrecord;
434 my $nextop="additem";
435 my @errors; # store errors found while checking data BEFORE saving item.
437 # Getting last created item cookie
438 my $prefillitem = C4::Context->preference('PrefillItem');
439 my $justaddeditem;
440 my $cookieitemrecord;
441 if ($prefillitem) {
442 my $lastitemcookie = $input->cookie('LastCreatedItem');
443 if ($lastitemcookie) {
444 $lastitemcookie = uri_unescape($lastitemcookie);
445 eval {
446 if ( thaw($lastitemcookie) ) {
447 $cookieitemrecord = thaw($lastitemcookie);
448 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
451 if ($@) {
452 $lastitemcookie = 'undef' unless $lastitemcookie;
453 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
458 #-------------------------------------------------------------------------------
459 if ($op eq "additem") {
461 #-------------------------------------------------------------------------------
462 # rebuild
463 my @tags = $input->multi_param('tag');
464 my @subfields = $input->multi_param('subfield');
465 my @values = $input->multi_param('field_value');
466 # build indicator hash.
467 my @ind_tag = $input->multi_param('ind_tag');
468 my @indicator = $input->multi_param('indicator');
469 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
470 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
472 # type of add
473 my $add_submit = $input->param('add_submit');
474 my $add_duplicate_submit = $input->param('add_duplicate_submit');
475 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
476 my $number_of_copies = $input->param('number_of_copies');
478 # This is a bit tricky : if there is a cookie for the last created item and
479 # we just added an item, the cookie value is not correct yet (it will be updated
480 # next page). To prevent the form from being filled with outdated values, we
481 # force the use of "add and duplicate" feature, so the form will be filled with
482 # correct values.
483 $add_duplicate_submit = 1 if ($prefillitem);
484 $justaddeditem = 1;
486 # if autoBarcode is set to 'incremental', calculate barcode...
487 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
488 $record = _increment_barcode($record, $frameworkcode);
491 my $addedolditem = TransformMarcToKoha( $record );
493 # If we have to add or add & duplicate, we add the item
494 if ( $add_submit || $add_duplicate_submit ) {
496 # check for item barcode # being unique
497 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
498 push @errors, "barcode_not_unique" if ($exist_itemnumber);
500 # if barcode exists, don't create, but report The problem.
501 unless ($exist_itemnumber) {
502 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
503 set_item_default_location($oldbibitemnum);
505 # Pushing the last created item cookie back
506 if ($prefillitem && defined $record) {
507 my $itemcookie = $input->cookie(
508 -name => 'LastCreatedItem',
509 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
510 -value => uri_escape_utf8( freeze( $record ) ),
511 -HttpOnly => 1,
512 -expires => ''
515 $cookie = [ $cookie, $itemcookie ];
519 $nextop = "additem";
520 if ($exist_itemnumber) {
521 $itemrecord = $record;
525 # If we have to add & duplicate
526 if ($add_duplicate_submit) {
527 $itemrecord = $record;
528 if (C4::Context->preference('autoBarcode') eq 'incremental') {
529 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
531 else {
532 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
533 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
534 my $fieldItem = $itemrecord->field($tagfield);
535 $itemrecord->delete_field($fieldItem);
536 $fieldItem->delete_subfields($tagsubfield);
537 $itemrecord->insert_fields_ordered($fieldItem);
539 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
542 # If we have to add multiple copies
543 if ($add_multiple_copies_submit) {
545 use C4::Barcodes;
546 my $barcodeobj = C4::Barcodes->new;
547 my $copynumber = $addedolditem->{'copynumber'};
548 my $oldbarcode = $addedolditem->{'barcode'};
549 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
550 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
552 # If there is a barcode and we can't find their new values, we can't add multiple copies
553 my $testbarcode;
554 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
555 if ($oldbarcode && !$testbarcode) {
557 push @errors, "no_next_barcode";
558 $itemrecord = $record;
560 } else {
561 # We add each item
563 # For the first iteration
564 my $barcodevalue = $oldbarcode;
565 my $exist_itemnumber;
568 for (my $i = 0; $i < $number_of_copies;) {
570 # If there is a barcode
571 if ($barcodevalue) {
573 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
574 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
576 # Putting it into the record
577 if ($barcodevalue) {
578 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
579 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
580 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
581 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
582 # But when adding multiple copies we need to prefix it here,
583 # so we retrieve the homebranch from the item and prefix the barcode with it.
584 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
585 my $homebranch = $record->subfield($hb_field, $hb_subfield);
586 $barcodevalue = $homebranch . $barcodevalue;
588 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
591 # Checking if the barcode already exists
592 $exist_itemnumber = get_item_from_barcode($barcodevalue);
594 # Updating record with the new copynumber
595 if ( $copynumber ){
596 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
599 # Adding the item
600 if (!$exist_itemnumber) {
601 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
602 set_item_default_location($oldbibitemnum);
604 # We count the item only if it was really added
605 # That way, all items are added, even if there was some already existing barcodes
606 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
607 $i++;
608 # Only increment copynumber if item was really added
609 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
612 # Preparing the next iteration
613 $oldbarcode = $barcodevalue;
615 undef($itemrecord);
618 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
619 print $input->redirect(
620 '/cgi-bin/koha/circ/circulation.pl?'
621 .'borrowernumber='.$fa_circborrowernumber
622 .'&barcode='.uri_escape_utf8($fa_barcode)
623 .'&duedatespec='.$fa_duedatespec
624 .'&stickyduedate=1'
626 exit;
630 #-------------------------------------------------------------------------------
631 } elsif ($op eq "edititem") {
632 #-------------------------------------------------------------------------------
633 # retrieve item if exist => then, it's a modif
634 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
635 $nextop = "saveitem";
636 #-------------------------------------------------------------------------------
637 } elsif ($op eq "dupeitem") {
638 #-------------------------------------------------------------------------------
639 # retrieve item if exist => then, it's a modif
640 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
641 if (C4::Context->preference('autoBarcode') eq 'incremental') {
642 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
644 else {
645 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
646 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
647 my $fieldItem = $itemrecord->field($tagfield);
648 $itemrecord->delete_field($fieldItem);
649 $fieldItem->delete_subfields($tagsubfield);
650 $itemrecord->insert_fields_ordered($fieldItem);
653 #check for hidden subfield and remove them for the duplicated item
654 foreach my $field ($itemrecord->fields()){
655 my $tag = $field->{_tag};
656 foreach my $subfield ($field->subfields()){
657 my $subfieldtag = $subfield->[0];
658 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
659 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
660 my $fieldItem = $itemrecord->field($tag);
661 $itemrecord->delete_field($fieldItem);
662 $fieldItem->delete_subfields($subfieldtag);
663 $itemrecord->insert_fields_ordered($fieldItem);
668 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
669 $nextop = "additem";
670 #-------------------------------------------------------------------------------
671 } elsif ($op eq "delitem") {
672 #-------------------------------------------------------------------------------
673 # check that there is no issue on this item before deletion.
674 $error = &DelItemCheck( $biblionumber,$itemnumber);
675 if($error == 1){
676 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
677 }else{
678 push @errors,$error;
679 $nextop="additem";
681 #-------------------------------------------------------------------------------
682 } elsif ($op eq "delallitems") {
683 #-------------------------------------------------------------------------------
684 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber })->get_column('itemnumber');
685 foreach my $itemnumber ( @itemnumbers ) {
686 $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
687 next if $error == 1; # Means ok
688 push @errors,$error;
690 if ( @errors ) {
691 $nextop="additem";
692 } else {
693 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
694 my $views = { C4::Search::enabled_staff_search_views };
695 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
696 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
697 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
698 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
699 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
700 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
701 } else {
702 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
704 exit;
706 #-------------------------------------------------------------------------------
707 } elsif ($op eq "saveitem") {
708 #-------------------------------------------------------------------------------
709 # rebuild
710 my @tags = $input->multi_param('tag');
711 my @subfields = $input->multi_param('subfield');
712 my @values = $input->multi_param('field_value');
713 # build indicator hash.
714 my @ind_tag = $input->multi_param('ind_tag');
715 my @indicator = $input->multi_param('indicator');
716 # my $itemnumber = $input->param('itemnumber');
717 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
718 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
719 # MARC::Record builded => now, record in DB
720 # warn "R: ".$record->as_formatted;
721 # check that the barcode don't exist already
722 my $addedolditem = TransformMarcToKoha($itemtosave);
723 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
724 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
725 push @errors,"barcode_not_unique";
726 } else {
727 my $item = Koha::Items->find($itemnumber );
728 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
729 $itemnumber = q{};
730 my $olditemlost = $item->itemlost;
731 my $newitemlost = $newitem->{itemlost};
732 LostItem( $item->itemnumber, 'additem' )
733 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
735 $nextop="additem";
736 } elsif ($op eq "delinkitem"){
737 my $analyticfield = '773';
738 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
739 $analyticfield = '773';
740 } elsif ($marcflavour eq 'UNIMARC') {
741 $analyticfield = '461';
743 foreach my $field ($record->field($analyticfield)){
744 if ($field->subfield('9') eq $hostitemnumber){
745 $record->delete_field($field);
746 last;
749 my $modbibresult = ModBiblio($record, $biblionumber,'');
753 #-------------------------------------------------------------------------------
754 # build screen with existing items. and "new" one
755 #-------------------------------------------------------------------------------
757 # now, build existiing item list
758 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
759 #my @fields = $record->fields();
762 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
763 my @big_array;
764 #---- finds where items.itemnumber is stored
765 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
766 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
767 C4::Biblio::EmbedItemsInMarcBiblio({
768 marc_record => $temp,
769 biblionumber => $biblionumber });
770 my @fields = $temp->fields();
773 my @hostitemnumbers;
774 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
775 my $analyticfield = '773';
776 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
777 $analyticfield = '773';
778 } elsif ($marcflavour eq 'UNIMARC') {
779 $analyticfield = '461';
781 foreach my $hostfield ($temp->field($analyticfield)){
782 my $hostbiblionumber = $hostfield->subfield('0');
783 if ($hostbiblionumber){
784 my $hostrecord = GetMarcBiblio({
785 biblionumber => $hostbiblionumber,
786 embed_items => 1 });
787 if ($hostrecord) {
788 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
789 foreach my $hostitem ($hostrecord->field($itemfield)){
790 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
791 push (@fields, $hostitem);
792 push (@hostitemnumbers, $hostfield->subfield('9'));
800 foreach my $field (@fields) {
801 next if ( $field->tag() < 10 );
803 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
804 my %this_row;
805 # loop through each subfield
806 my $i = 0;
807 foreach my $subfield (@subf){
808 my $subfieldcode = $subfield->[0];
809 my $subfieldvalue= $subfield->[1];
811 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
812 && ($field->tag() ne $itemtagfield
813 && $subfieldcode ne $itemtagsubfield));
814 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
815 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
816 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
817 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
818 $subfieldcode, $subfieldvalue, '', $tagslib)
819 || $subfieldvalue;
822 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
823 #verifying rights
824 my $userenv = C4::Context->userenv();
825 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
826 $this_row{'nomod'} = 1;
829 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
831 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
832 foreach my $hostitemnumber (@hostitemnumbers) {
833 my $item = Koha::Items->find( $hostitemnumber );
834 if ($this_row{itemnumber} eq $hostitemnumber) {
835 $this_row{hostitemflag} = 1;
836 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
837 last;
842 if (%this_row) {
843 push(@big_array, \%this_row);
847 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
848 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
850 # now, construct template !
851 # First, the existing items for display
852 my @item_value_loop;
853 my @header_value_loop;
854 for my $row ( @big_array ) {
855 my %row_data;
856 my @item_fields;
857 foreach my $key (sort keys %witness){
858 my $item_field;
859 if ( $row->{$key} ){
860 $item_field->{field} = $row->{$key};
861 } else {
862 $item_field->{field} = '';
865 for my $kohafield (
866 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
869 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
870 next unless $key eq $subfield;
871 $item_field->{datatype} = 'date';
874 push @item_fields, $item_field;
876 $row_data{item_value} = [ @item_fields ];
877 $row_data{itemnumber} = $row->{itemnumber};
878 #reporting this_row values
879 $row_data{'nomod'} = $row->{'nomod'};
880 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
881 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
882 # $row_data{'countanalytics'} = $row->{'countanalytics'};
883 push(@item_value_loop,\%row_data);
885 foreach my $subfield_code (sort keys(%witness)) {
886 my %header_value;
887 $header_value{header_value} = $witness{$subfield_code};
889 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
890 my $kohafield = $subfieldlib->{kohafield};
891 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
892 $header_value{column_name} = $1;
895 push(@header_value_loop, \%header_value);
898 # now, build the item form for entering a new item
899 my @loop_data =();
900 my $i=0;
902 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
904 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
905 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
906 for my $library ( @$libraries ) {
907 $library->{selected} = 1 if $library->{branchcode} eq $branch
910 # We generate form, from actuel record
911 @fields = ();
912 if($itemrecord){
913 foreach my $field ($itemrecord->fields()){
914 my $tag = $field->{_tag};
915 foreach my $subfield ( $field->subfields() ){
917 my $subfieldtag = $subfield->[0];
918 my $value = $subfield->[1];
919 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
921 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
923 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
924 push @fields, "$tag$subfieldtag";
925 push (@loop_data, $subfield_data);
926 $i++;
931 # and now we add fields that are empty
933 # Using last created item if it exists
935 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
937 # We generate form, and fill with values if defined
938 foreach my $tag ( keys %{$tagslib}){
939 foreach my $subtag (keys %{$tagslib->{$tag}}){
940 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
941 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
942 next if any { /^$tag$subtag$/ } @fields;
944 my @values = (undef);
945 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
946 for my $value (@values){
947 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
948 push (@loop_data, $subfield_data);
949 $i++;
953 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
955 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
957 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
958 $template->param(
959 biblionumber => $biblionumber,
960 title => $oldrecord->{title},
961 author => $oldrecord->{author},
962 item_loop => \@item_value_loop,
963 item_header_loop => \@header_value_loop,
964 item => \@loop_data,
965 itemnumber => $itemnumber,
966 barcode => $item ? $item->barcode : undef,
967 itemtagfield => $itemtagfield,
968 itemtagsubfield => $itemtagsubfield,
969 op => $nextop,
970 popup => scalar $input->param('popup') ? 1: 0,
971 C4::Search::enabled_staff_search_views,
973 $template->{'VARS'}->{'searchid'} = $searchid;
975 if ($frameworkcode eq 'FA'){
976 # fast cataloguing datas
977 $template->param(
978 'circborrowernumber' => $fa_circborrowernumber,
979 'barcode' => $fa_barcode,
980 'branch' => $fa_branch,
981 'stickyduedate' => $fa_stickyduedate,
982 'duedatespec' => $fa_duedatespec,
986 foreach my $error (@errors) {
987 $template->param($error => 1);
989 output_html_with_http_headers $input, $cookie, $template->output;