Add 20.11 release team
[koha.git] / cataloguing / additem.pl
blobb0ce8b58c5cb2172bf643737461828d862ed2677
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 $item->permanent_location($item->location);
80 $item->location(C4::Context->preference('NewItemsDefaultLocation'));
82 else {
83 # It seems that we are dealing with that in too many places
84 $item->permanent_location($item->location) unless defined $item->permanent_location;
86 $item->store;
89 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
90 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
91 sub _increment_barcode {
92 my ($record, $frameworkcode) = @_;
93 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
94 unless ($record->field($tagfield)->subfield($tagsubfield)) {
95 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
96 $sth_barcode->execute;
97 my ($newbarcode) = $sth_barcode->fetchrow;
98 $newbarcode++;
99 # OK, we have the new barcode, now create the entry in MARC record
100 my $fieldItem = $record->field($tagfield);
101 $record->delete_field($fieldItem);
102 $fieldItem->add_subfields($tagsubfield => $newbarcode);
103 $record->insert_fields_ordered($fieldItem);
105 return $record;
109 sub generate_subfield_form {
110 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
112 my $frameworkcode = &GetFrameworkCode($biblionumber);
114 my %subfield_data;
115 my $dbh = C4::Context->dbh;
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;
124 $subfield_data{tag} = $tag;
125 $subfield_data{subfield} = $subfieldtag;
126 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
127 $subfield_data{mandatory} = $subfieldlib->{mandatory};
128 $subfield_data{important} = $subfieldlib->{important};
129 $subfield_data{repeatable} = $subfieldlib->{repeatable};
130 $subfield_data{maxlength} = $subfieldlib->{maxlength};
132 if ( ! defined( $value ) || $value eq '') {
133 $value = $subfieldlib->{defaultvalue};
134 if ( $value ) {
135 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
136 my $today_dt = dt_from_string;
137 my $year = $today_dt->strftime('%Y');
138 my $month = $today_dt->strftime('%m');
139 my $day = $today_dt->strftime('%d');
140 $value =~ s/<<YYYY>>/$year/g;
141 $value =~ s/<<MM>>/$month/g;
142 $value =~ s/<<DD>>/$day/g;
143 # And <<USER>> with surname (?)
144 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
145 $value=~s/<<USER>>/$username/g;
149 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
151 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
152 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
153 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
154 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
155 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
156 my $temp2 = $temp->field($CNtag);
158 next unless $temp2;
159 $value = $temp2->as_string( $CNsubfields, ' ' );
160 last if $value;
164 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
165 my $input = new CGI;
166 $value = $input->param('barcode');
169 if ( $subfieldlib->{authorised_value} ) {
170 my @authorised_values;
171 my %authorised_lib;
172 # builds list, depending on authorised value...
173 if ( $subfieldlib->{authorised_value} eq "branches" ) {
174 foreach my $thisbranch (@$branches) {
175 push @authorised_values, $thisbranch->{branchcode};
176 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
177 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
180 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
181 push @authorised_values, "";
182 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
183 my $itemtypes;
184 if($branch_limit) {
185 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
186 } else {
187 $itemtypes = Koha::ItemTypes->search_with_localization;
189 while ( my $itemtype = $itemtypes->next ) {
190 push @authorised_values, $itemtype->itemtype;
191 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
194 unless ( $value ) {
195 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
196 $itype_sth->execute( $biblionumber );
197 ( $value ) = $itype_sth->fetchrow_array;
200 #---- class_sources
202 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
203 push @authorised_values, "";
205 my $class_sources = GetClassSources();
206 my $default_source = C4::Context->preference("DefaultClassificationSource");
208 foreach my $class_source (sort keys %$class_sources) {
209 next unless $class_sources->{$class_source}->{'used'} or
210 ($value and $class_source eq $value) or
211 ($class_source eq $default_source);
212 push @authorised_values, $class_source;
213 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
215 $value = $default_source unless ($value);
217 #---- "true" authorised value
219 else {
220 push @authorised_values, qq{};
221 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
222 for my $r ( @$av ) {
223 push @authorised_values, $r->{authorised_value};
224 $authorised_lib{$r->{authorised_value}} = $r->{lib};
228 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
229 $subfield_data{marc_value} = {
230 type => 'hidden',
231 id => $subfield_data{id},
232 maxlength => $subfield_data{maxlength},
233 value => $value,
236 else {
237 $subfield_data{marc_value} = {
238 type => 'select',
239 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
240 values => \@authorised_values,
241 labels => \%authorised_lib,
242 default => $value,
246 # it's a thesaurus / authority field
247 elsif ( $subfieldlib->{authtypecode} ) {
248 $subfield_data{marc_value} = {
249 type => 'text_auth',
250 id => $subfield_data{id},
251 maxlength => $subfield_data{maxlength},
252 value => $value,
253 authtypecode => $subfieldlib->{authtypecode},
256 # it's a plugin field
257 elsif ( $subfieldlib->{value_builder} ) { # plugin
258 require Koha::FrameworkPlugin;
259 my $plugin = Koha::FrameworkPlugin->new({
260 name => $subfieldlib->{'value_builder'},
261 item_style => 1,
263 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
264 id => $subfield_data{id}, tabloop => $loop_data };
265 $plugin->build( $pars );
266 if( !$plugin->errstr ) {
267 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
268 $subfield_data{marc_value} = {
269 type => 'text_plugin',
270 id => $subfield_data{id},
271 maxlength => $subfield_data{maxlength},
272 value => $value,
273 class => $class,
274 nopopup => $plugin->noclick,
275 javascript => $plugin->javascript,
277 } else {
278 warn $plugin->errstr;
279 $subfield_data{marc_value} = {
280 type => 'text',
281 id => $subfield_data{id},
282 maxlength => $subfield_data{maxlength},
283 value => $value,
284 }; # supply default input form
287 elsif ( $tag eq '' ) { # it's an hidden field
288 $subfield_data{marc_value} = {
289 type => 'hidden',
290 id => $subfield_data{id},
291 maxlength => $subfield_data{maxlength},
292 value => $value,
295 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
296 $subfield_data{marc_value} = {
297 type => 'text',
298 id => $subfield_data{id},
299 maxlength => $subfield_data{maxlength},
300 value => $value,
303 elsif (
305 $value and length($value) > 100
307 or (
308 C4::Context->preference("marcflavour") eq "UNIMARC"
309 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
311 or (
312 C4::Context->preference("marcflavour") eq "MARC21"
313 and 500 <= $tag && $tag < 600
316 # oversize field (textarea)
317 $subfield_data{marc_value} = {
318 type => 'textarea',
319 id => $subfield_data{id},
320 value => $value,
322 } else {
323 # it's a standard field
324 $subfield_data{marc_value} = {
325 type => 'text',
326 id => $subfield_data{id},
327 maxlength => $subfield_data{maxlength},
328 value => $value,
332 # Getting list of subfields to keep when restricted editing is enabled
333 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
334 my $allowAllSubfields = (
335 not defined $subfieldsToAllowForRestrictedEditing
336 or $subfieldsToAllowForRestrictedEditing eq q||
337 ) ? 1 : 0;
338 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
340 # If we're on restricted editing, and our field is not in the list of subfields to allow,
341 # then it is read-only
342 $subfield_data{marc_value}->{readonly} = (
343 not $allowAllSubfields
344 and $restrictededition
345 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
346 ) ? 1: 0;
348 return \%subfield_data;
351 # Removes some subfields when prefilling items
352 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
353 sub removeFieldsForPrefill {
355 my $item = shift;
357 # Getting item tag
358 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
360 # Getting list of subfields to keep
361 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
363 # Removing subfields that are not in the syspref
364 if ($tag && $subfieldsToUseWhenPrefill) {
365 my $field = $item->field($tag);
366 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
367 foreach my $subfield ($field->subfields()) {
368 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
369 $field->delete_subfield(code => $subfield->[0]);
375 return $item;
379 my $input = new CGI;
380 my $error = $input->param('error');
381 my $biblionumber = $input->param('biblionumber');
382 my $itemnumber = $input->param('itemnumber');
383 my $op = $input->param('op') || q{};
384 my $hostitemnumber = $input->param('hostitemnumber');
385 my $marcflavour = C4::Context->preference("marcflavour");
386 my $searchid = $input->param('searchid');
387 # fast cataloguing datas
388 my $fa_circborrowernumber = $input->param('circborrowernumber');
389 my $fa_barcode = $input->param('barcode');
390 my $fa_branch = $input->param('branch');
391 my $fa_stickyduedate = $input->param('stickyduedate');
392 my $fa_duedatespec = $input->param('duedatespec');
394 my $frameworkcode = &GetFrameworkCode($biblionumber);
396 # Defining which userflag is needing according to the framework currently used
397 my $userflags;
398 if (defined $input->param('frameworkcode')) {
399 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
402 if (not defined $userflags) {
403 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
406 my ($template, $loggedinuser, $cookie)
407 = get_template_and_user({template_name => "cataloguing/additem.tt",
408 query => $input,
409 type => "intranet",
410 authnotrequired => 0,
411 flagsrequired => {editcatalogue => $userflags},
412 debug => 1,
416 # Does the user have a restricted item editing permission?
417 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
418 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
419 # In case user is a superlibrarian, editing is not restricted
420 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
421 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
422 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
424 my $tagslib = &GetMarcStructure(1,$frameworkcode);
425 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
427 output_and_exit_if_error( $input, $cookie, $template,
428 { module => 'cataloguing', record => $record } );
430 my $oldrecord = TransformMarcToKoha($record);
431 my $itemrecord;
432 my $nextop="additem";
433 my @errors; # store errors found while checking data BEFORE saving item.
435 # Getting last created item cookie
436 my $prefillitem = C4::Context->preference('PrefillItem');
437 my $justaddeditem;
438 my $cookieitemrecord;
439 if ($prefillitem) {
440 my $lastitemcookie = $input->cookie('LastCreatedItem');
441 if ($lastitemcookie) {
442 $lastitemcookie = uri_unescape($lastitemcookie);
443 eval {
444 if ( thaw($lastitemcookie) ) {
445 $cookieitemrecord = thaw($lastitemcookie);
446 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
449 if ($@) {
450 $lastitemcookie = 'undef' unless $lastitemcookie;
451 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
456 #-------------------------------------------------------------------------------
457 if ($op eq "additem") {
459 #-------------------------------------------------------------------------------
460 # rebuild
461 my @tags = $input->multi_param('tag');
462 my @subfields = $input->multi_param('subfield');
463 my @values = $input->multi_param('field_value');
464 # build indicator hash.
465 my @ind_tag = $input->multi_param('ind_tag');
466 my @indicator = $input->multi_param('indicator');
467 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
468 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
470 # type of add
471 my $add_submit = $input->param('add_submit');
472 my $add_duplicate_submit = $input->param('add_duplicate_submit');
473 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
474 my $number_of_copies = $input->param('number_of_copies');
476 # This is a bit tricky : if there is a cookie for the last created item and
477 # we just added an item, the cookie value is not correct yet (it will be updated
478 # next page). To prevent the form from being filled with outdated values, we
479 # force the use of "add and duplicate" feature, so the form will be filled with
480 # correct values.
481 $add_duplicate_submit = 1 if ($prefillitem);
482 $justaddeditem = 1;
484 # if autoBarcode is set to 'incremental', calculate barcode...
485 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
486 $record = _increment_barcode($record, $frameworkcode);
489 my $addedolditem = TransformMarcToKoha( $record );
491 # If we have to add or add & duplicate, we add the item
492 if ( $add_submit || $add_duplicate_submit ) {
494 # check for item barcode # being unique
495 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
496 push @errors, "barcode_not_unique" if ($exist_itemnumber);
498 # if barcode exists, don't create, but report The problem.
499 unless ($exist_itemnumber) {
500 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
501 set_item_default_location($oldbibitemnum);
503 # Pushing the last created item cookie back
504 if ($prefillitem && defined $record) {
505 my $itemcookie = $input->cookie(
506 -name => 'LastCreatedItem',
507 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
508 -value => uri_escape_utf8( freeze( $record ) ),
509 -HttpOnly => 1,
510 -expires => ''
513 $cookie = [ $cookie, $itemcookie ];
517 $nextop = "additem";
518 if ($exist_itemnumber) {
519 $itemrecord = $record;
523 # If we have to add & duplicate
524 if ($add_duplicate_submit) {
525 $itemrecord = $record;
526 if (C4::Context->preference('autoBarcode') eq 'incremental') {
527 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
529 else {
530 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
531 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
532 my $fieldItem = $itemrecord->field($tagfield);
533 $itemrecord->delete_field($fieldItem);
534 $fieldItem->delete_subfields($tagsubfield);
535 $itemrecord->insert_fields_ordered($fieldItem);
537 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
540 # If we have to add multiple copies
541 if ($add_multiple_copies_submit) {
543 use C4::Barcodes;
544 my $barcodeobj = C4::Barcodes->new;
545 my $copynumber = $addedolditem->{'copynumber'};
546 my $oldbarcode = $addedolditem->{'barcode'};
547 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
548 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
550 # If there is a barcode and we can't find their new values, we can't add multiple copies
551 my $testbarcode;
552 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
553 if ($oldbarcode && !$testbarcode) {
555 push @errors, "no_next_barcode";
556 $itemrecord = $record;
558 } else {
559 # We add each item
561 # For the first iteration
562 my $barcodevalue = $oldbarcode;
563 my $exist_itemnumber;
566 for (my $i = 0; $i < $number_of_copies;) {
568 # If there is a barcode
569 if ($barcodevalue) {
571 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
572 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
574 # Putting it into the record
575 if ($barcodevalue) {
576 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
577 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
578 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
579 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
580 # But when adding multiple copies we need to prefix it here,
581 # so we retrieve the homebranch from the item and prefix the barcode with it.
582 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
583 my $homebranch = $record->subfield($hb_field, $hb_subfield);
584 $barcodevalue = $homebranch . $barcodevalue;
586 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
589 # Checking if the barcode already exists
590 $exist_itemnumber = get_item_from_barcode($barcodevalue);
592 # Updating record with the new copynumber
593 if ( $copynumber ){
594 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
597 # Adding the item
598 if (!$exist_itemnumber) {
599 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
600 AddItemFromMarc( $record, $biblionumber, { skip_modzebra_update => 1 } );
601 set_item_default_location($oldbibitemnum);
603 # We count the item only if it was really added
604 # That way, all items are added, even if there was some already existing barcodes
605 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
606 $i++;
607 # Only increment copynumber if item was really added
608 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
611 # Preparing the next iteration
612 $oldbarcode = $barcodevalue;
615 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
617 undef($itemrecord);
620 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
621 print $input->redirect(
622 '/cgi-bin/koha/circ/circulation.pl?'
623 .'borrowernumber='.$fa_circborrowernumber
624 .'&barcode='.uri_escape_utf8($fa_barcode)
625 .'&duedatespec='.$fa_duedatespec
626 .'&stickyduedate=1'
628 exit;
632 #-------------------------------------------------------------------------------
633 } elsif ($op eq "edititem") {
634 #-------------------------------------------------------------------------------
635 # retrieve item if exist => then, it's a modif
636 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
637 $nextop = "saveitem";
638 #-------------------------------------------------------------------------------
639 } elsif ($op eq "dupeitem") {
640 #-------------------------------------------------------------------------------
641 # retrieve item if exist => then, it's a modif
642 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
643 if (C4::Context->preference('autoBarcode') eq 'incremental') {
644 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
646 else {
647 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
648 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
649 my $fieldItem = $itemrecord->field($tagfield);
650 $itemrecord->delete_field($fieldItem);
651 $fieldItem->delete_subfields($tagsubfield);
652 $itemrecord->insert_fields_ordered($fieldItem);
655 #check for hidden subfield and remove them for the duplicated item
656 foreach my $field ($itemrecord->fields()){
657 my $tag = $field->{_tag};
658 foreach my $subfield ($field->subfields()){
659 my $subfieldtag = $subfield->[0];
660 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
661 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
662 my $fieldItem = $itemrecord->field($tag);
663 $itemrecord->delete_field($fieldItem);
664 $fieldItem->delete_subfields($subfieldtag);
665 $itemrecord->insert_fields_ordered($fieldItem);
670 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
671 $nextop = "additem";
672 #-------------------------------------------------------------------------------
673 } elsif ($op eq "delitem") {
674 #-------------------------------------------------------------------------------
675 # check that there is no issue on this item before deletion.
676 my $item = Koha::Items->find($itemnumber);
677 $error = $item->safe_delete;
678 if(ref($error) eq 'Koha::Item'){
679 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
680 }else{
681 push @errors,$error;
682 $nextop="additem";
684 #-------------------------------------------------------------------------------
685 } elsif ($op eq "delallitems") {
686 #-------------------------------------------------------------------------------
687 my $items = Koha::Items->search({ biblionumber => $biblionumber });
688 while ( my $item = $items->next ) {
689 $error = $item->safe_delete({ skip_modzebra_update => 1 });
690 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
691 push @errors,$error;
693 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
694 if ( @errors ) {
695 $nextop="additem";
696 } else {
697 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
698 my $views = { C4::Search::enabled_staff_search_views };
699 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
700 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
701 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
702 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
703 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
704 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
705 } else {
706 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
708 exit;
710 #-------------------------------------------------------------------------------
711 } elsif ($op eq "saveitem") {
712 #-------------------------------------------------------------------------------
713 # rebuild
714 my @tags = $input->multi_param('tag');
715 my @subfields = $input->multi_param('subfield');
716 my @values = $input->multi_param('field_value');
717 # build indicator hash.
718 my @ind_tag = $input->multi_param('ind_tag');
719 my @indicator = $input->multi_param('indicator');
720 # my $itemnumber = $input->param('itemnumber');
721 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
722 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
723 # MARC::Record builded => now, record in DB
724 # warn "R: ".$record->as_formatted;
725 # check that the barcode don't exist already
726 my $addedolditem = TransformMarcToKoha($itemtosave);
727 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
728 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
729 push @errors,"barcode_not_unique";
730 } else {
731 my $item = Koha::Items->find($itemnumber );
732 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
733 $itemnumber = q{};
734 my $olditemlost = $item->itemlost;
735 my $newitemlost = $newitem->{itemlost};
736 LostItem( $item->itemnumber, 'additem' )
737 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
739 $nextop="additem";
740 } elsif ($op eq "delinkitem"){
741 my $analyticfield = '773';
742 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
743 $analyticfield = '773';
744 } elsif ($marcflavour eq 'UNIMARC') {
745 $analyticfield = '461';
747 foreach my $field ($record->field($analyticfield)){
748 if ($field->subfield('9') eq $hostitemnumber){
749 $record->delete_field($field);
750 last;
753 my $modbibresult = ModBiblio($record, $biblionumber,'');
757 #-------------------------------------------------------------------------------
758 # build screen with existing items. and "new" one
759 #-------------------------------------------------------------------------------
761 # now, build existiing item list
762 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
763 #my @fields = $record->fields();
766 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
767 my @big_array;
768 #---- finds where items.itemnumber is stored
769 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
770 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
771 C4::Biblio::EmbedItemsInMarcBiblio({
772 marc_record => $temp,
773 biblionumber => $biblionumber });
774 my @fields = $temp->fields();
777 my @hostitemnumbers;
778 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
779 my $analyticfield = '773';
780 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
781 $analyticfield = '773';
782 } elsif ($marcflavour eq 'UNIMARC') {
783 $analyticfield = '461';
785 foreach my $hostfield ($temp->field($analyticfield)){
786 my $hostbiblionumber = $hostfield->subfield('0');
787 if ($hostbiblionumber){
788 my $hostrecord = GetMarcBiblio({
789 biblionumber => $hostbiblionumber,
790 embed_items => 1 });
791 if ($hostrecord) {
792 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
793 foreach my $hostitem ($hostrecord->field($itemfield)){
794 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
795 push (@fields, $hostitem);
796 push (@hostitemnumbers, $hostfield->subfield('9'));
804 foreach my $field (@fields) {
805 next if ( $field->tag() < 10 );
807 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
808 my %this_row;
809 # loop through each subfield
810 my $i = 0;
811 foreach my $subfield (@subf){
812 my $subfieldcode = $subfield->[0];
813 my $subfieldvalue= $subfield->[1];
815 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
816 && ($field->tag() ne $itemtagfield
817 && $subfieldcode ne $itemtagsubfield));
818 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
819 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
820 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
821 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
822 $subfieldcode, $subfieldvalue, '', $tagslib)
823 || $subfieldvalue;
826 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
827 #verifying rights
828 my $userenv = C4::Context->userenv();
829 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
830 $this_row{'nomod'} = 1;
833 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
835 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
836 foreach my $hostitemnumber (@hostitemnumbers) {
837 my $item = Koha::Items->find( $hostitemnumber );
838 if ($this_row{itemnumber} eq $hostitemnumber) {
839 $this_row{hostitemflag} = 1;
840 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
841 last;
846 if (%this_row) {
847 push(@big_array, \%this_row);
851 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
852 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
854 # now, construct template !
855 # First, the existing items for display
856 my @item_value_loop;
857 my @header_value_loop;
858 for my $row ( @big_array ) {
859 my %row_data;
860 my @item_fields;
861 foreach my $key (sort keys %witness){
862 my $item_field;
863 if ( $row->{$key} ){
864 $item_field->{field} = $row->{$key};
865 } else {
866 $item_field->{field} = '';
869 for my $kohafield (
870 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
873 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
874 next unless $key eq $subfield;
875 $item_field->{field} = output_pref( { str => $row->{$key}, dateonly => 1 } );
878 push @item_fields, $item_field;
880 $row_data{item_value} = [ @item_fields ];
881 $row_data{itemnumber} = $row->{itemnumber};
882 #reporting this_row values
883 $row_data{'nomod'} = $row->{'nomod'};
884 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
885 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
886 # $row_data{'countanalytics'} = $row->{'countanalytics'};
887 push(@item_value_loop,\%row_data);
889 foreach my $subfield_code (sort keys(%witness)) {
890 my %header_value;
891 $header_value{header_value} = $witness{$subfield_code};
893 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
894 my $kohafield = $subfieldlib->{kohafield};
895 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
896 $header_value{column_name} = $1;
899 push(@header_value_loop, \%header_value);
902 # now, build the item form for entering a new item
903 my @loop_data =();
904 my $i=0;
906 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
907 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
908 for my $library ( @$libraries ) {
909 $library->{selected} = 1 if $library->{branchcode} eq $branch
912 # We generate form, from actuel record
913 @fields = ();
914 if($itemrecord){
915 foreach my $field ($itemrecord->fields()){
916 my $tag = $field->{_tag};
917 foreach my $subfield ( $field->subfields() ){
919 my $subfieldtag = $subfield->[0];
920 my $value = $subfield->[1];
921 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
923 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
925 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
926 push @fields, "$tag$subfieldtag";
927 push (@loop_data, $subfield_data);
928 $i++;
933 # and now we add fields that are empty
935 # Using last created item if it exists
937 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
939 # We generate form, and fill with values if defined
940 foreach my $tag ( keys %{$tagslib}){
941 foreach my $subtag (keys %{$tagslib->{$tag}}){
942 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
943 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
944 next if any { /^$tag$subtag$/ } @fields;
946 my @values = (undef);
947 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
948 for my $value (@values){
949 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
950 push (@loop_data, $subfield_data);
951 $i++;
955 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
957 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
959 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
960 $template->param(
961 biblionumber => $biblionumber,
962 title => $oldrecord->{title},
963 author => $oldrecord->{author},
964 item_loop => \@item_value_loop,
965 item_header_loop => \@header_value_loop,
966 item => \@loop_data,
967 itemnumber => $itemnumber,
968 barcode => $item ? $item->barcode : undef,
969 itemtagfield => $itemtagfield,
970 itemtagsubfield => $itemtagsubfield,
971 op => $nextop,
972 popup => scalar $input->param('popup') ? 1: 0,
973 C4::Search::enabled_staff_search_views,
975 $template->{'VARS'}->{'searchid'} = $searchid;
977 if ($frameworkcode eq 'FA'){
978 # fast cataloguing datas
979 $template->param(
980 'circborrowernumber' => $fa_circborrowernumber,
981 'barcode' => $fa_barcode,
982 'branch' => $fa_branch,
983 'stickyduedate' => $fa_stickyduedate,
984 'duedatespec' => $fa_duedatespec,
988 foreach my $error (@errors) {
989 $template->param($error => 1);
991 output_html_with_http_headers $input, $cookie, $template->output;