Bug 18501: Add _set_found_trigger
[koha.git] / cataloguing / additem.pl
bloba9710891680a445b00e2102c683ec214d5e4c371
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,
252 else {
253 $subfield_data{marc_value} = {
254 type => 'select',
255 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
256 values => \@authorised_values,
257 labels => \%authorised_lib,
258 default => $value,
262 # it's a thesaurus / authority field
263 elsif ( $subfieldlib->{authtypecode} ) {
264 $subfield_data{marc_value} = {
265 type => 'text_auth',
266 id => $subfield_data{id},
267 maxlength => $subfield_data{maxlength},
268 value => $value,
269 authtypecode => $subfieldlib->{authtypecode},
272 # it's a plugin field
273 elsif ( $subfieldlib->{value_builder} ) { # plugin
274 require Koha::FrameworkPlugin;
275 my $plugin = Koha::FrameworkPlugin->new({
276 name => $subfieldlib->{'value_builder'},
277 item_style => 1,
279 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
280 id => $subfield_data{id}, tabloop => $loop_data };
281 $plugin->build( $pars );
282 if( !$plugin->errstr ) {
283 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
284 $subfield_data{marc_value} = {
285 type => 'text_plugin',
286 id => $subfield_data{id},
287 maxlength => $subfield_data{maxlength},
288 value => $value,
289 class => $class,
290 nopopup => $plugin->noclick,
291 javascript => $plugin->javascript,
293 } else {
294 warn $plugin->errstr;
295 $subfield_data{marc_value} = {
296 type => 'text',
297 id => $subfield_data{id},
298 maxlength => $subfield_data{maxlength},
299 value => $value,
300 }; # supply default input form
303 elsif ( $tag eq '' ) { # it's an hidden field
304 $subfield_data{marc_value} = {
305 type => 'hidden',
306 id => $subfield_data{id},
307 maxlength => $subfield_data{maxlength},
308 value => $value,
311 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
312 $subfield_data{marc_value} = {
313 type => 'text',
314 id => $subfield_data{id},
315 maxlength => $subfield_data{maxlength},
316 value => $value,
319 elsif (
321 $value and length($value) > 100
323 or (
324 C4::Context->preference("marcflavour") eq "UNIMARC"
325 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
327 or (
328 C4::Context->preference("marcflavour") eq "MARC21"
329 and 500 <= $tag && $tag < 600
332 # oversize field (textarea)
333 $subfield_data{marc_value} = {
334 type => 'textarea',
335 id => $subfield_data{id},
336 value => $value,
338 } else {
339 # it's a standard field
340 $subfield_data{marc_value} = {
341 type => 'text',
342 id => $subfield_data{id},
343 maxlength => $subfield_data{maxlength},
344 value => $value,
348 # Getting list of subfields to keep when restricted editing is enabled
349 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
350 my $allowAllSubfields = (
351 not defined $subfieldsToAllowForRestrictedEditing
352 or $subfieldsToAllowForRestrictedEditing eq q||
353 ) ? 1 : 0;
354 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
356 # If we're on restricted editing, and our field is not in the list of subfields to allow,
357 # then it is read-only
358 $subfield_data{marc_value}->{readonly} = (
359 not $allowAllSubfields
360 and $restrictededition
361 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
362 ) ? 1: 0;
364 return \%subfield_data;
367 # Removes some subfields when prefilling items
368 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
369 sub removeFieldsForPrefill {
371 my $item = shift;
373 # Getting item tag
374 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
376 # Getting list of subfields to keep
377 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
379 # Removing subfields that are not in the syspref
380 if ($tag && $subfieldsToUseWhenPrefill) {
381 my $field = $item->field($tag);
382 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
383 foreach my $subfield ($field->subfields()) {
384 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
385 $field->delete_subfield(code => $subfield->[0]);
391 return $item;
395 my $input = new CGI;
396 my $error = $input->param('error');
397 my $biblionumber = $input->param('biblionumber');
398 my $itemnumber = $input->param('itemnumber');
399 my $op = $input->param('op') || q{};
400 my $hostitemnumber = $input->param('hostitemnumber');
401 my $marcflavour = C4::Context->preference("marcflavour");
402 my $searchid = $input->param('searchid');
403 # fast cataloguing datas
404 my $fa_circborrowernumber = $input->param('circborrowernumber');
405 my $fa_barcode = $input->param('barcode');
406 my $fa_branch = $input->param('branch');
407 my $fa_stickyduedate = $input->param('stickyduedate');
408 my $fa_duedatespec = $input->param('duedatespec');
410 my $frameworkcode = &GetFrameworkCode($biblionumber);
412 # Defining which userflag is needing according to the framework currently used
413 my $userflags;
414 if (defined $input->param('frameworkcode')) {
415 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
418 if (not defined $userflags) {
419 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
422 my ($template, $loggedinuser, $cookie)
423 = get_template_and_user({template_name => "cataloguing/additem.tt",
424 query => $input,
425 type => "intranet",
426 authnotrequired => 0,
427 flagsrequired => {editcatalogue => $userflags},
428 debug => 1,
432 # Does the user have a restricted item editing permission?
433 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
434 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
435 # In case user is a superlibrarian, editing is not restricted
436 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
437 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
438 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
440 my $tagslib = &GetMarcStructure(1,$frameworkcode);
441 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
443 output_and_exit_if_error( $input, $cookie, $template,
444 { module => 'cataloguing', record => $record } );
446 my $oldrecord = TransformMarcToKoha($record);
447 my $itemrecord;
448 my $nextop="additem";
449 my @errors; # store errors found while checking data BEFORE saving item.
451 # Getting last created item cookie
452 my $prefillitem = C4::Context->preference('PrefillItem');
453 my $justaddeditem;
454 my $cookieitemrecord;
455 if ($prefillitem) {
456 my $lastitemcookie = $input->cookie('LastCreatedItem');
457 if ($lastitemcookie) {
458 $lastitemcookie = uri_unescape($lastitemcookie);
459 eval {
460 if ( thaw($lastitemcookie) ) {
461 $cookieitemrecord = thaw($lastitemcookie);
462 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
465 if ($@) {
466 $lastitemcookie = 'undef' unless $lastitemcookie;
467 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
472 #-------------------------------------------------------------------------------
473 if ($op eq "additem") {
475 #-------------------------------------------------------------------------------
476 # rebuild
477 my @tags = $input->multi_param('tag');
478 my @subfields = $input->multi_param('subfield');
479 my @values = $input->multi_param('field_value');
480 # build indicator hash.
481 my @ind_tag = $input->multi_param('ind_tag');
482 my @indicator = $input->multi_param('indicator');
483 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
484 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
486 # type of add
487 my $add_submit = $input->param('add_submit');
488 my $add_duplicate_submit = $input->param('add_duplicate_submit');
489 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
490 my $number_of_copies = $input->param('number_of_copies');
492 # This is a bit tricky : if there is a cookie for the last created item and
493 # we just added an item, the cookie value is not correct yet (it will be updated
494 # next page). To prevent the form from being filled with outdated values, we
495 # force the use of "add and duplicate" feature, so the form will be filled with
496 # correct values.
497 $add_duplicate_submit = 1 if ($prefillitem);
498 $justaddeditem = 1;
500 # if autoBarcode is set to 'incremental', calculate barcode...
501 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
502 $record = _increment_barcode($record, $frameworkcode);
505 my $addedolditem = TransformMarcToKoha( $record );
507 # If we have to add or add & duplicate, we add the item
508 if ( $add_submit || $add_duplicate_submit ) {
510 # check for item barcode # being unique
511 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
512 push @errors, "barcode_not_unique" if ($exist_itemnumber);
514 # if barcode exists, don't create, but report The problem.
515 unless ($exist_itemnumber) {
516 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
517 set_item_default_location($oldbibitemnum);
519 # Pushing the last created item cookie back
520 if ($prefillitem && defined $record) {
521 my $itemcookie = $input->cookie(
522 -name => 'LastCreatedItem',
523 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
524 -value => uri_escape_utf8( freeze( $record ) ),
525 -HttpOnly => 1,
526 -expires => ''
529 $cookie = [ $cookie, $itemcookie ];
533 $nextop = "additem";
534 if ($exist_itemnumber) {
535 $itemrecord = $record;
539 # If we have to add & duplicate
540 if ($add_duplicate_submit) {
541 $itemrecord = $record;
542 if (C4::Context->preference('autoBarcode') eq 'incremental') {
543 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
545 else {
546 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
547 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
548 my $fieldItem = $itemrecord->field($tagfield);
549 $itemrecord->delete_field($fieldItem);
550 $fieldItem->delete_subfields($tagsubfield);
551 $itemrecord->insert_fields_ordered($fieldItem);
553 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
556 # If we have to add multiple copies
557 if ($add_multiple_copies_submit) {
559 use C4::Barcodes;
560 my $barcodeobj = C4::Barcodes->new;
561 my $copynumber = $addedolditem->{'copynumber'};
562 my $oldbarcode = $addedolditem->{'barcode'};
563 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
564 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
566 # If there is a barcode and we can't find their new values, we can't add multiple copies
567 my $testbarcode;
568 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
569 if ($oldbarcode && !$testbarcode) {
571 push @errors, "no_next_barcode";
572 $itemrecord = $record;
574 } else {
575 # We add each item
577 # For the first iteration
578 my $barcodevalue = $oldbarcode;
579 my $exist_itemnumber;
582 for (my $i = 0; $i < $number_of_copies;) {
584 # If there is a barcode
585 if ($barcodevalue) {
587 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
588 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
590 # Putting it into the record
591 if ($barcodevalue) {
592 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
593 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
594 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
595 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
596 # But when adding multiple copies we need to prefix it here,
597 # so we retrieve the homebranch from the item and prefix the barcode with it.
598 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
599 my $homebranch = $record->subfield($hb_field, $hb_subfield);
600 $barcodevalue = $homebranch . $barcodevalue;
602 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
605 # Checking if the barcode already exists
606 $exist_itemnumber = get_item_from_barcode($barcodevalue);
608 # Updating record with the new copynumber
609 if ( $copynumber ){
610 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
613 # Adding the item
614 if (!$exist_itemnumber) {
615 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
616 AddItemFromMarc( $record, $biblionumber, { skip_modzebra_update => 1 } );
617 set_item_default_location($oldbibitemnum);
619 # We count the item only if it was really added
620 # That way, all items are added, even if there was some already existing barcodes
621 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
622 $i++;
623 # Only increment copynumber if item was really added
624 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
627 # Preparing the next iteration
628 $oldbarcode = $barcodevalue;
631 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
633 undef($itemrecord);
636 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
637 print $input->redirect(
638 '/cgi-bin/koha/circ/circulation.pl?'
639 .'borrowernumber='.$fa_circborrowernumber
640 .'&barcode='.uri_escape_utf8($fa_barcode)
641 .'&duedatespec='.$fa_duedatespec
642 .'&stickyduedate=1'
644 exit;
648 #-------------------------------------------------------------------------------
649 } elsif ($op eq "edititem") {
650 #-------------------------------------------------------------------------------
651 # retrieve item if exist => then, it's a modif
652 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
653 $nextop = "saveitem";
654 #-------------------------------------------------------------------------------
655 } elsif ($op eq "dupeitem") {
656 #-------------------------------------------------------------------------------
657 # retrieve item if exist => then, it's a modif
658 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
659 if (C4::Context->preference('autoBarcode') eq 'incremental') {
660 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
662 else {
663 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
664 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
665 my $fieldItem = $itemrecord->field($tagfield);
666 $itemrecord->delete_field($fieldItem);
667 $fieldItem->delete_subfields($tagsubfield);
668 $itemrecord->insert_fields_ordered($fieldItem);
671 #check for hidden subfield and remove them for the duplicated item
672 foreach my $field ($itemrecord->fields()){
673 my $tag = $field->{_tag};
674 foreach my $subfield ($field->subfields()){
675 my $subfieldtag = $subfield->[0];
676 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
677 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
678 my $fieldItem = $itemrecord->field($tag);
679 $itemrecord->delete_field($fieldItem);
680 $fieldItem->delete_subfields($subfieldtag);
681 $itemrecord->insert_fields_ordered($fieldItem);
686 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
687 $nextop = "additem";
688 #-------------------------------------------------------------------------------
689 } elsif ($op eq "delitem") {
690 #-------------------------------------------------------------------------------
691 # check that there is no issue on this item before deletion.
692 my $item = Koha::Items->find($itemnumber);
693 $error = $item->safe_delete;
694 if(ref($error) eq 'Koha::Item'){
695 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
696 }else{
697 push @errors,$error;
698 $nextop="additem";
700 #-------------------------------------------------------------------------------
701 } elsif ($op eq "delallitems") {
702 #-------------------------------------------------------------------------------
703 my $items = Koha::Items->search({ biblionumber => $biblionumber });
704 while ( my $item = $items->next ) {
705 $error = $item->safe_delete({ skip_modzebra_update => 1 });
706 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
707 push @errors,$error;
709 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
710 if ( @errors ) {
711 $nextop="additem";
712 } else {
713 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
714 my $views = { C4::Search::enabled_staff_search_views };
715 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
716 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
717 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
718 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
719 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
720 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
721 } else {
722 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
724 exit;
726 #-------------------------------------------------------------------------------
727 } elsif ($op eq "saveitem") {
728 #-------------------------------------------------------------------------------
729 # rebuild
730 my @tags = $input->multi_param('tag');
731 my @subfields = $input->multi_param('subfield');
732 my @values = $input->multi_param('field_value');
733 # build indicator hash.
734 my @ind_tag = $input->multi_param('ind_tag');
735 my @indicator = $input->multi_param('indicator');
736 # my $itemnumber = $input->param('itemnumber');
737 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
738 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
739 # MARC::Record builded => now, record in DB
740 # warn "R: ".$record->as_formatted;
741 # check that the barcode don't exist already
742 my $addedolditem = TransformMarcToKoha($itemtosave);
743 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
744 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
745 push @errors,"barcode_not_unique";
746 } else {
747 my $item = Koha::Items->find($itemnumber );
748 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
749 $itemnumber = q{};
750 my $olditemlost = $item->itemlost;
751 my $newitemlost = $newitem->{itemlost};
752 if ( $newitemlost && $newitemlost ge '1' && !$olditemlost ) {
753 LostItem( $item->itemnumber, 'additem' )
756 $nextop="additem";
757 } elsif ($op eq "delinkitem"){
758 my $analyticfield = '773';
759 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
760 $analyticfield = '773';
761 } elsif ($marcflavour eq 'UNIMARC') {
762 $analyticfield = '461';
764 foreach my $field ($record->field($analyticfield)){
765 if ($field->subfield('9') eq $hostitemnumber){
766 $record->delete_field($field);
767 last;
770 my $modbibresult = ModBiblio($record, $biblionumber,'');
774 #-------------------------------------------------------------------------------
775 # build screen with existing items. and "new" one
776 #-------------------------------------------------------------------------------
778 # now, build existiing item list
779 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
780 #my @fields = $record->fields();
783 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
784 my @big_array;
785 #---- finds where items.itemnumber is stored
786 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
787 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
788 C4::Biblio::EmbedItemsInMarcBiblio({
789 marc_record => $temp,
790 biblionumber => $biblionumber });
791 my @fields = $temp->fields();
794 my @hostitemnumbers;
795 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
796 my $analyticfield = '773';
797 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
798 $analyticfield = '773';
799 } elsif ($marcflavour eq 'UNIMARC') {
800 $analyticfield = '461';
802 foreach my $hostfield ($temp->field($analyticfield)){
803 my $hostbiblionumber = $hostfield->subfield('0');
804 if ($hostbiblionumber){
805 my $hostrecord = GetMarcBiblio({
806 biblionumber => $hostbiblionumber,
807 embed_items => 1 });
808 if ($hostrecord) {
809 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
810 foreach my $hostitem ($hostrecord->field($itemfield)){
811 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
812 push (@fields, $hostitem);
813 push (@hostitemnumbers, $hostfield->subfield('9'));
821 foreach my $field (@fields) {
822 next if ( $field->tag() < 10 );
824 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
825 my %this_row;
826 # loop through each subfield
827 my $i = 0;
828 foreach my $subfield (@subf){
829 my $subfieldcode = $subfield->[0];
830 my $subfieldvalue= $subfield->[1];
832 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
833 && ($field->tag() ne $itemtagfield
834 && $subfieldcode ne $itemtagsubfield));
835 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
836 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
837 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
838 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
839 $subfieldcode, $subfieldvalue, '', $tagslib)
840 || $subfieldvalue;
843 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
844 #verifying rights
845 my $userenv = C4::Context->userenv();
846 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
847 $this_row{'nomod'} = 1;
850 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
852 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
853 foreach my $hostitemnumber (@hostitemnumbers) {
854 my $item = Koha::Items->find( $hostitemnumber );
855 if ($this_row{itemnumber} eq $hostitemnumber) {
856 $this_row{hostitemflag} = 1;
857 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
858 last;
863 if (%this_row) {
864 push(@big_array, \%this_row);
868 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
869 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
871 # now, construct template !
872 # First, the existing items for display
873 my @item_value_loop;
874 my @header_value_loop;
875 for my $row ( @big_array ) {
876 my %row_data;
877 my @item_fields;
878 foreach my $key (sort keys %witness){
879 my $item_field;
880 if ( $row->{$key} ){
881 $item_field->{field} = $row->{$key};
882 } else {
883 $item_field->{field} = '';
886 for my $kohafield (
887 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
890 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
891 next unless $key eq $subfield;
892 $item_field->{datatype} = 'date';
895 push @item_fields, $item_field;
897 $row_data{item_value} = [ @item_fields ];
898 $row_data{itemnumber} = $row->{itemnumber};
899 #reporting this_row values
900 $row_data{'nomod'} = $row->{'nomod'};
901 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
902 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
903 # $row_data{'countanalytics'} = $row->{'countanalytics'};
904 push(@item_value_loop,\%row_data);
906 foreach my $subfield_code (sort keys(%witness)) {
907 my %header_value;
908 $header_value{header_value} = $witness{$subfield_code};
910 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
911 my $kohafield = $subfieldlib->{kohafield};
912 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
913 $header_value{column_name} = $1;
916 push(@header_value_loop, \%header_value);
919 # now, build the item form for entering a new item
920 my @loop_data =();
921 my $i=0;
923 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
924 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
925 for my $library ( @$libraries ) {
926 $library->{selected} = 1 if $library->{branchcode} eq $branch
929 my $item = Koha::Items->find($itemnumber);
931 # We generate form, from actuel record
932 @fields = ();
933 if($itemrecord){
934 foreach my $field ($itemrecord->fields()){
935 my $tag = $field->{_tag};
936 foreach my $subfield ( $field->subfields() ){
938 my $subfieldtag = $subfield->[0];
939 my $value = $subfield->[1];
940 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
942 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
944 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
945 push @fields, "$tag$subfieldtag";
946 push (@loop_data, $subfield_data);
947 $i++;
952 # and now we add fields that are empty
954 # Using last created item if it exists
956 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
958 # We generate form, and fill with values if defined
959 foreach my $tag ( keys %{$tagslib}){
960 foreach my $subtag (keys %{$tagslib->{$tag}}){
961 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
962 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
963 next if any { /^$tag$subtag$/ } @fields;
965 my @values = (undef);
966 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
967 for my $value (@values){
968 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
969 push (@loop_data, $subfield_data);
970 $i++;
974 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
976 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
977 $template->param(
978 biblionumber => $biblionumber,
979 title => $oldrecord->{title},
980 author => $oldrecord->{author},
981 item_loop => \@item_value_loop,
982 item_header_loop => \@header_value_loop,
983 item => \@loop_data,
984 itemnumber => $itemnumber,
985 barcode => $item ? $item->barcode : undef,
986 itemtagfield => $itemtagfield,
987 itemtagsubfield => $itemtagsubfield,
988 op => $nextop,
989 popup => scalar $input->param('popup') ? 1: 0,
990 C4::Search::enabled_staff_search_views,
992 $template->{'VARS'}->{'searchid'} = $searchid;
994 if ($frameworkcode eq 'FA'){
995 # fast cataloguing datas
996 $template->param(
997 'circborrowernumber' => $fa_circborrowernumber,
998 'barcode' => $fa_barcode,
999 'branch' => $fa_branch,
1000 'stickyduedate' => $fa_stickyduedate,
1001 'duedatespec' => $fa_duedatespec,
1005 foreach my $error (@errors) {
1006 $template->param($error => 1);
1008 output_html_with_http_headers $input, $cookie, $template->output;