Bug 25728: Create AV when adding a new item
[koha.git] / cataloguing / additem.pl
blob2d0ba7e3975b4eed5d9041823576985395840a94
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, $item) = @_;
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>>, <<YY>>, <<MM>>, <<DD>> if provided in the default value
136 my $today_dt = dt_from_string;
137 my $year = $today_dt->strftime('%Y');
138 my $shortyear = $today_dt->strftime('%y');
139 my $month = $today_dt->strftime('%m');
140 my $day = $today_dt->strftime('%d');
141 $value =~ s/<<YYYY>>/$year/g;
142 $value =~ s/<<YY>>/$shortyear/g;
143 $value =~ s/<<MM>>/$month/g;
144 $value =~ s/<<DD>>/$day/g;
145 # And <<USER>> with surname (?)
146 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
147 $value=~s/<<USER>>/$username/g;
151 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
153 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
154 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
155 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
156 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
157 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
158 my $temp2 = $temp->field($CNtag);
160 next unless $temp2;
161 $value = $temp2->as_string( $CNsubfields, ' ' );
162 last if $value;
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 "LOST" ) {
176 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
177 my $item_is_return_claim = $ClaimReturnedLostValue && $item && $item->itemlost && $ClaimReturnedLostValue eq $item->itemlost;
178 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
180 $subfield_data{IS_LOST_AV} = 1;
182 push @authorised_values, qq{};
183 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
184 for my $r ( @$av ) {
185 push @authorised_values, $r->{authorised_value};
186 $authorised_lib{$r->{authorised_value}} = $r->{lib};
189 elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
190 foreach my $thisbranch (@$branches) {
191 push @authorised_values, $thisbranch->{branchcode};
192 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
193 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
196 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
197 push @authorised_values, "";
198 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
199 my $itemtypes;
200 if($branch_limit) {
201 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
202 } else {
203 $itemtypes = Koha::ItemTypes->search_with_localization;
205 while ( my $itemtype = $itemtypes->next ) {
206 push @authorised_values, $itemtype->itemtype;
207 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
210 unless ( $value ) {
211 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
212 $itype_sth->execute( $biblionumber );
213 ( $value ) = $itype_sth->fetchrow_array;
216 #---- class_sources
218 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
219 push @authorised_values, "";
221 my $class_sources = GetClassSources();
222 my $default_source = C4::Context->preference("DefaultClassificationSource");
224 foreach my $class_source (sort keys %$class_sources) {
225 next unless $class_sources->{$class_source}->{'used'} or
226 ($value and $class_source eq $value) or
227 ($class_source eq $default_source);
228 push @authorised_values, $class_source;
229 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
231 $value = $default_source unless ($value);
233 #---- "true" authorised value
235 else {
236 push @authorised_values, qq{};
237 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
238 for my $r ( @$av ) {
239 push @authorised_values, $r->{authorised_value};
240 $authorised_lib{$r->{authorised_value}} = $r->{lib};
244 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
245 $subfield_data{marc_value} = {
246 type => 'hidden',
247 id => $subfield_data{id},
248 maxlength => $subfield_data{maxlength},
249 value => $value,
250 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
253 else {
254 $subfield_data{marc_value} = {
255 type => 'select',
256 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
257 values => \@authorised_values,
258 labels => \%authorised_lib,
259 default => $value,
260 ( ( grep { $_ eq $subfieldlib->{authorised_value}} ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $subfieldlib->{authorised_value}) ),
264 # it's a thesaurus / authority field
265 elsif ( $subfieldlib->{authtypecode} ) {
266 $subfield_data{marc_value} = {
267 type => 'text_auth',
268 id => $subfield_data{id},
269 maxlength => $subfield_data{maxlength},
270 value => $value,
271 authtypecode => $subfieldlib->{authtypecode},
274 # it's a plugin field
275 elsif ( $subfieldlib->{value_builder} ) { # plugin
276 require Koha::FrameworkPlugin;
277 my $plugin = Koha::FrameworkPlugin->new({
278 name => $subfieldlib->{'value_builder'},
279 item_style => 1,
281 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
282 id => $subfield_data{id}, tabloop => $loop_data };
283 $plugin->build( $pars );
284 if( !$plugin->errstr ) {
285 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
286 $subfield_data{marc_value} = {
287 type => 'text_plugin',
288 id => $subfield_data{id},
289 maxlength => $subfield_data{maxlength},
290 value => $value,
291 class => $class,
292 nopopup => $plugin->noclick,
293 javascript => $plugin->javascript,
295 } else {
296 warn $plugin->errstr;
297 $subfield_data{marc_value} = {
298 type => 'text',
299 id => $subfield_data{id},
300 maxlength => $subfield_data{maxlength},
301 value => $value,
302 }; # supply default input form
305 elsif ( $tag eq '' ) { # it's an hidden field
306 $subfield_data{marc_value} = {
307 type => 'hidden',
308 id => $subfield_data{id},
309 maxlength => $subfield_data{maxlength},
310 value => $value,
313 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
314 $subfield_data{marc_value} = {
315 type => 'text',
316 id => $subfield_data{id},
317 maxlength => $subfield_data{maxlength},
318 value => $value,
321 elsif (
323 $value and length($value) > 100
325 or (
326 C4::Context->preference("marcflavour") eq "UNIMARC"
327 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
329 or (
330 C4::Context->preference("marcflavour") eq "MARC21"
331 and 500 <= $tag && $tag < 600
334 # oversize field (textarea)
335 $subfield_data{marc_value} = {
336 type => 'textarea',
337 id => $subfield_data{id},
338 value => $value,
340 } else {
341 # it's a standard field
342 $subfield_data{marc_value} = {
343 type => 'text',
344 id => $subfield_data{id},
345 maxlength => $subfield_data{maxlength},
346 value => $value,
350 # Getting list of subfields to keep when restricted editing is enabled
351 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
352 my $allowAllSubfields = (
353 not defined $subfieldsToAllowForRestrictedEditing
354 or $subfieldsToAllowForRestrictedEditing eq q||
355 ) ? 1 : 0;
356 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
358 # If we're on restricted editing, and our field is not in the list of subfields to allow,
359 # then it is read-only
360 $subfield_data{marc_value}->{readonly} = (
361 not $allowAllSubfields
362 and $restrictededition
363 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
364 ) ? 1: 0;
366 return \%subfield_data;
369 # Removes some subfields when prefilling items
370 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
371 sub removeFieldsForPrefill {
373 my $item = shift;
375 # Getting item tag
376 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
378 # Getting list of subfields to keep
379 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
381 # Removing subfields that are not in the syspref
382 if ($tag && $subfieldsToUseWhenPrefill) {
383 my $field = $item->field($tag);
384 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
385 foreach my $subfield ($field->subfields()) {
386 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
387 $field->delete_subfield(code => $subfield->[0]);
393 return $item;
397 my $input = new CGI;
398 my $error = $input->param('error');
399 my $biblionumber = $input->param('biblionumber');
400 my $itemnumber = $input->param('itemnumber');
401 my $op = $input->param('op') || q{};
402 my $hostitemnumber = $input->param('hostitemnumber');
403 my $marcflavour = C4::Context->preference("marcflavour");
404 my $searchid = $input->param('searchid');
405 # fast cataloguing datas
406 my $fa_circborrowernumber = $input->param('circborrowernumber');
407 my $fa_barcode = $input->param('barcode');
408 my $fa_branch = $input->param('branch');
409 my $fa_stickyduedate = $input->param('stickyduedate');
410 my $fa_duedatespec = $input->param('duedatespec');
412 my $frameworkcode = &GetFrameworkCode($biblionumber);
414 # Defining which userflag is needing according to the framework currently used
415 my $userflags;
416 if (defined $input->param('frameworkcode')) {
417 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
420 if (not defined $userflags) {
421 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
424 my ($template, $loggedinuser, $cookie)
425 = get_template_and_user({template_name => "cataloguing/additem.tt",
426 query => $input,
427 type => "intranet",
428 authnotrequired => 0,
429 flagsrequired => {editcatalogue => $userflags},
430 debug => 1,
434 # Does the user have a restricted item editing permission?
435 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
436 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
437 # In case user is a superlibrarian, editing is not restricted
438 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
439 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
440 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
442 my $tagslib = &GetMarcStructure(1,$frameworkcode);
443 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
445 output_and_exit_if_error( $input, $cookie, $template,
446 { module => 'cataloguing', record => $record } );
448 my $oldrecord = TransformMarcToKoha($record);
449 my $itemrecord;
450 my $nextop="additem";
451 my @errors; # store errors found while checking data BEFORE saving item.
453 # Getting last created item cookie
454 my $prefillitem = C4::Context->preference('PrefillItem');
455 my $justaddeditem;
456 my $cookieitemrecord;
457 if ($prefillitem) {
458 my $lastitemcookie = $input->cookie('LastCreatedItem');
459 if ($lastitemcookie) {
460 $lastitemcookie = uri_unescape($lastitemcookie);
461 eval {
462 if ( thaw($lastitemcookie) ) {
463 $cookieitemrecord = thaw($lastitemcookie);
464 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
467 if ($@) {
468 $lastitemcookie = 'undef' unless $lastitemcookie;
469 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
474 #-------------------------------------------------------------------------------
475 if ($op eq "additem") {
477 #-------------------------------------------------------------------------------
478 # rebuild
479 my @tags = $input->multi_param('tag');
480 my @subfields = $input->multi_param('subfield');
481 my @values = $input->multi_param('field_value');
482 # build indicator hash.
483 my @ind_tag = $input->multi_param('ind_tag');
484 my @indicator = $input->multi_param('indicator');
485 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
486 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
488 # type of add
489 my $add_submit = $input->param('add_submit');
490 my $add_duplicate_submit = $input->param('add_duplicate_submit');
491 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
492 my $number_of_copies = $input->param('number_of_copies');
494 # This is a bit tricky : if there is a cookie for the last created item and
495 # we just added an item, the cookie value is not correct yet (it will be updated
496 # next page). To prevent the form from being filled with outdated values, we
497 # force the use of "add and duplicate" feature, so the form will be filled with
498 # correct values.
499 $add_duplicate_submit = 1 if ($prefillitem);
500 $justaddeditem = 1;
502 # if autoBarcode is set to 'incremental', calculate barcode...
503 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
504 $record = _increment_barcode($record, $frameworkcode);
507 my $addedolditem = TransformMarcToKoha( $record );
509 # If we have to add or add & duplicate, we add the item
510 if ( $add_submit || $add_duplicate_submit ) {
512 # check for item barcode # being unique
513 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
514 push @errors, "barcode_not_unique" if ($exist_itemnumber);
516 # if barcode exists, don't create, but report The problem.
517 unless ($exist_itemnumber) {
518 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
519 set_item_default_location($oldbibitemnum);
521 # Pushing the last created item cookie back
522 if ($prefillitem && defined $record) {
523 my $itemcookie = $input->cookie(
524 -name => 'LastCreatedItem',
525 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
526 -value => uri_escape_utf8( freeze( $record ) ),
527 -HttpOnly => 1,
528 -expires => ''
531 $cookie = [ $cookie, $itemcookie ];
535 $nextop = "additem";
536 if ($exist_itemnumber) {
537 $itemrecord = $record;
541 # If we have to add & duplicate
542 if ($add_duplicate_submit) {
543 $itemrecord = $record;
544 if (C4::Context->preference('autoBarcode') eq 'incremental') {
545 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
547 else {
548 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
549 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
550 my $fieldItem = $itemrecord->field($tagfield);
551 $itemrecord->delete_field($fieldItem);
552 $fieldItem->delete_subfields($tagsubfield);
553 $itemrecord->insert_fields_ordered($fieldItem);
555 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
558 # If we have to add multiple copies
559 if ($add_multiple_copies_submit) {
561 use C4::Barcodes;
562 my $barcodeobj = C4::Barcodes->new;
563 my $copynumber = $addedolditem->{'copynumber'};
564 my $oldbarcode = $addedolditem->{'barcode'};
565 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
566 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
568 # If there is a barcode and we can't find their new values, we can't add multiple copies
569 my $testbarcode;
570 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
571 if ($oldbarcode && !$testbarcode) {
573 push @errors, "no_next_barcode";
574 $itemrecord = $record;
576 } else {
577 # We add each item
579 # For the first iteration
580 my $barcodevalue = $oldbarcode;
581 my $exist_itemnumber;
584 for (my $i = 0; $i < $number_of_copies;) {
586 # If there is a barcode
587 if ($barcodevalue) {
589 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
590 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
592 # Putting it into the record
593 if ($barcodevalue) {
594 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
595 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
596 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
597 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
598 # But when adding multiple copies we need to prefix it here,
599 # so we retrieve the homebranch from the item and prefix the barcode with it.
600 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
601 my $homebranch = $record->subfield($hb_field, $hb_subfield);
602 $barcodevalue = $homebranch . $barcodevalue;
604 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
607 # Checking if the barcode already exists
608 $exist_itemnumber = get_item_from_barcode($barcodevalue);
610 # Updating record with the new copynumber
611 if ( $copynumber ){
612 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
615 # Adding the item
616 if (!$exist_itemnumber) {
617 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
618 AddItemFromMarc( $record, $biblionumber, { skip_modzebra_update => 1 } );
619 set_item_default_location($oldbibitemnum);
621 # We count the item only if it was really added
622 # That way, all items are added, even if there was some already existing barcodes
623 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
624 $i++;
625 # Only increment copynumber if item was really added
626 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
629 # Preparing the next iteration
630 $oldbarcode = $barcodevalue;
633 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
635 undef($itemrecord);
638 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
639 print $input->redirect(
640 '/cgi-bin/koha/circ/circulation.pl?'
641 .'borrowernumber='.$fa_circborrowernumber
642 .'&barcode='.uri_escape_utf8($fa_barcode)
643 .'&duedatespec='.$fa_duedatespec
644 .'&stickyduedate=1'
646 exit;
650 #-------------------------------------------------------------------------------
651 } elsif ($op eq "edititem") {
652 #-------------------------------------------------------------------------------
653 # retrieve item if exist => then, it's a modif
654 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
655 $nextop = "saveitem";
656 #-------------------------------------------------------------------------------
657 } elsif ($op eq "dupeitem") {
658 #-------------------------------------------------------------------------------
659 # retrieve item if exist => then, it's a modif
660 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
661 if (C4::Context->preference('autoBarcode') eq 'incremental') {
662 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
664 else {
665 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
666 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
667 my $fieldItem = $itemrecord->field($tagfield);
668 $itemrecord->delete_field($fieldItem);
669 $fieldItem->delete_subfields($tagsubfield);
670 $itemrecord->insert_fields_ordered($fieldItem);
673 #check for hidden subfield and remove them for the duplicated item
674 foreach my $field ($itemrecord->fields()){
675 my $tag = $field->{_tag};
676 foreach my $subfield ($field->subfields()){
677 my $subfieldtag = $subfield->[0];
678 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
679 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
680 my $fieldItem = $itemrecord->field($tag);
681 $itemrecord->delete_field($fieldItem);
682 $fieldItem->delete_subfields($subfieldtag);
683 $itemrecord->insert_fields_ordered($fieldItem);
688 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
689 $nextop = "additem";
690 #-------------------------------------------------------------------------------
691 } elsif ($op eq "delitem") {
692 #-------------------------------------------------------------------------------
693 # check that there is no issue on this item before deletion.
694 my $item = Koha::Items->find($itemnumber);
695 $error = $item->safe_delete;
696 if(ref($error) eq 'Koha::Item'){
697 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
698 }else{
699 push @errors,$error;
700 $nextop="additem";
702 #-------------------------------------------------------------------------------
703 } elsif ($op eq "delallitems") {
704 #-------------------------------------------------------------------------------
705 my $items = Koha::Items->search({ biblionumber => $biblionumber });
706 while ( my $item = $items->next ) {
707 $error = $item->safe_delete({ skip_modzebra_update => 1 });
708 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
709 push @errors,$error;
711 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
712 if ( @errors ) {
713 $nextop="additem";
714 } else {
715 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
716 my $views = { C4::Search::enabled_staff_search_views };
717 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
718 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
719 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
720 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
721 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
722 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
723 } else {
724 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
726 exit;
728 #-------------------------------------------------------------------------------
729 } elsif ($op eq "saveitem") {
730 #-------------------------------------------------------------------------------
731 # rebuild
732 my @tags = $input->multi_param('tag');
733 my @subfields = $input->multi_param('subfield');
734 my @values = $input->multi_param('field_value');
735 # build indicator hash.
736 my @ind_tag = $input->multi_param('ind_tag');
737 my @indicator = $input->multi_param('indicator');
738 # my $itemnumber = $input->param('itemnumber');
739 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
740 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
741 # MARC::Record builded => now, record in DB
742 # warn "R: ".$record->as_formatted;
743 # check that the barcode don't exist already
744 my $addedolditem = TransformMarcToKoha($itemtosave);
745 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
746 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
747 push @errors,"barcode_not_unique";
748 } else {
749 my $item = Koha::Items->find($itemnumber );
750 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
751 $itemnumber = q{};
752 my $olditemlost = $item->itemlost;
753 my $newitemlost = $newitem->{itemlost};
754 if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
755 LostItem( $item->itemnumber, 'additem' )
758 $nextop="additem";
759 } elsif ($op eq "delinkitem"){
760 my $analyticfield = '773';
761 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
762 $analyticfield = '773';
763 } elsif ($marcflavour eq 'UNIMARC') {
764 $analyticfield = '461';
766 foreach my $field ($record->field($analyticfield)){
767 if ($field->subfield('9') eq $hostitemnumber){
768 $record->delete_field($field);
769 last;
772 my $modbibresult = ModBiblio($record, $biblionumber,'');
776 #-------------------------------------------------------------------------------
777 # build screen with existing items. and "new" one
778 #-------------------------------------------------------------------------------
780 # now, build existiing item list
781 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
782 #my @fields = $record->fields();
785 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
786 my @big_array;
787 #---- finds where items.itemnumber is stored
788 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
789 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
790 C4::Biblio::EmbedItemsInMarcBiblio({
791 marc_record => $temp,
792 biblionumber => $biblionumber });
793 my @fields = $temp->fields();
796 my @hostitemnumbers;
797 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
798 my $analyticfield = '773';
799 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
800 $analyticfield = '773';
801 } elsif ($marcflavour eq 'UNIMARC') {
802 $analyticfield = '461';
804 foreach my $hostfield ($temp->field($analyticfield)){
805 my $hostbiblionumber = $hostfield->subfield('0');
806 if ($hostbiblionumber){
807 my $hostrecord = GetMarcBiblio({
808 biblionumber => $hostbiblionumber,
809 embed_items => 1 });
810 if ($hostrecord) {
811 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
812 foreach my $hostitem ($hostrecord->field($itemfield)){
813 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
814 push (@fields, $hostitem);
815 push (@hostitemnumbers, $hostfield->subfield('9'));
823 foreach my $field (@fields) {
824 next if ( $field->tag() < 10 );
826 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
827 my %this_row;
828 # loop through each subfield
829 my $i = 0;
830 foreach my $subfield (@subf){
831 my $subfieldcode = $subfield->[0];
832 my $subfieldvalue= $subfield->[1];
834 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
835 && ($field->tag() ne $itemtagfield
836 && $subfieldcode ne $itemtagsubfield));
837 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
838 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
839 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
840 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
841 $subfieldcode, $subfieldvalue, '', $tagslib)
842 || $subfieldvalue;
845 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
846 #verifying rights
847 my $userenv = C4::Context->userenv();
848 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
849 $this_row{'nomod'} = 1;
852 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
854 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
855 foreach my $hostitemnumber (@hostitemnumbers) {
856 my $item = Koha::Items->find( $hostitemnumber );
857 if ($this_row{itemnumber} eq $hostitemnumber) {
858 $this_row{hostitemflag} = 1;
859 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
860 last;
865 if (%this_row) {
866 push(@big_array, \%this_row);
870 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
871 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
873 # now, construct template !
874 # First, the existing items for display
875 my @item_value_loop;
876 my @header_value_loop;
877 for my $row ( @big_array ) {
878 my %row_data;
879 my @item_fields;
880 foreach my $key (sort keys %witness){
881 my $item_field;
882 if ( $row->{$key} ){
883 $item_field->{field} = $row->{$key};
884 } else {
885 $item_field->{field} = '';
888 for my $kohafield (
889 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
892 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
893 next unless $key eq $subfield;
894 $item_field->{datatype} = 'date';
897 push @item_fields, $item_field;
899 $row_data{item_value} = [ @item_fields ];
900 $row_data{itemnumber} = $row->{itemnumber};
901 #reporting this_row values
902 $row_data{'nomod'} = $row->{'nomod'};
903 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
904 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
905 # $row_data{'countanalytics'} = $row->{'countanalytics'};
906 push(@item_value_loop,\%row_data);
908 foreach my $subfield_code (sort keys(%witness)) {
909 my %header_value;
910 $header_value{header_value} = $witness{$subfield_code};
912 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
913 my $kohafield = $subfieldlib->{kohafield};
914 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
915 $header_value{column_name} = $1;
918 push(@header_value_loop, \%header_value);
921 # now, build the item form for entering a new item
922 my @loop_data =();
923 my $i=0;
925 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
926 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
927 for my $library ( @$libraries ) {
928 $library->{selected} = 1 if $library->{branchcode} eq $branch
931 my $item = Koha::Items->find($itemnumber);
933 # We generate form, from actuel record
934 @fields = ();
935 if($itemrecord){
936 foreach my $field ($itemrecord->fields()){
937 my $tag = $field->{_tag};
938 foreach my $subfield ( $field->subfields() ){
940 my $subfieldtag = $subfield->[0];
941 my $value = $subfield->[1];
942 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
944 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
946 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
947 push @fields, "$tag$subfieldtag";
948 push (@loop_data, $subfield_data);
949 $i++;
954 # and now we add fields that are empty
956 # Using last created item if it exists
958 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
960 # We generate form, and fill with values if defined
961 foreach my $tag ( keys %{$tagslib}){
962 foreach my $subtag (keys %{$tagslib->{$tag}}){
963 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
964 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
965 next if any { /^$tag$subtag$/ } @fields;
967 my @values = (undef);
968 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
969 for my $value (@values){
970 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
971 push (@loop_data, $subfield_data);
972 $i++;
976 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
978 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
979 $template->param(
980 biblionumber => $biblionumber,
981 title => $oldrecord->{title},
982 author => $oldrecord->{author},
983 item_loop => \@item_value_loop,
984 item_header_loop => \@header_value_loop,
985 item => \@loop_data,
986 itemnumber => $itemnumber,
987 barcode => $item ? $item->barcode : undef,
988 itemtagfield => $itemtagfield,
989 itemtagsubfield => $itemtagsubfield,
990 op => $nextop,
991 popup => scalar $input->param('popup') ? 1: 0,
992 C4::Search::enabled_staff_search_views,
994 $template->{'VARS'}->{'searchid'} = $searchid;
996 if ($frameworkcode eq 'FA'){
997 # fast cataloguing datas
998 $template->param(
999 'circborrowernumber' => $fa_circborrowernumber,
1000 'barcode' => $fa_barcode,
1001 'branch' => $fa_branch,
1002 'stickyduedate' => $fa_stickyduedate,
1003 'duedatespec' => $fa_duedatespec,
1007 foreach my $error (@errors) {
1008 $template->param($error => 1);
1010 output_html_with_http_headers $input, $cookie, $template->output;