Bug 25811: (follow-up) Debug - Paste the source of the page
[koha.git] / cataloguing / additem.pl
blob001d9d8c15a18e0ef2f3ea61876e070605f4a6f9
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>>, <<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 "LOST" ) {
174 my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue');
175 my $item_is_return_claim = $ClaimReturnedLostValue && $item && $item->itemlost && $ClaimReturnedLostValue eq $item->itemlost;
176 $subfield_data{IS_RETURN_CLAIM} = $item_is_return_claim;
178 $subfield_data{IS_LOST_AV} = 1;
180 push @authorised_values, qq{};
181 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
182 for my $r ( @$av ) {
183 push @authorised_values, $r->{authorised_value};
184 $authorised_lib{$r->{authorised_value}} = $r->{lib};
187 elsif ( $subfieldlib->{authorised_value} eq "branches" ) {
188 foreach my $thisbranch (@$branches) {
189 push @authorised_values, $thisbranch->{branchcode};
190 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
191 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
194 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
195 push @authorised_values, "";
196 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
197 my $itemtypes;
198 if($branch_limit) {
199 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
200 } else {
201 $itemtypes = Koha::ItemTypes->search_with_localization;
203 while ( my $itemtype = $itemtypes->next ) {
204 push @authorised_values, $itemtype->itemtype;
205 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
208 unless ( $value ) {
209 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
210 $itype_sth->execute( $biblionumber );
211 ( $value ) = $itype_sth->fetchrow_array;
214 #---- class_sources
216 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
217 push @authorised_values, "";
219 my $class_sources = GetClassSources();
220 my $default_source = C4::Context->preference("DefaultClassificationSource");
222 foreach my $class_source (sort keys %$class_sources) {
223 next unless $class_sources->{$class_source}->{'used'} or
224 ($value and $class_source eq $value) or
225 ($class_source eq $default_source);
226 push @authorised_values, $class_source;
227 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
229 $value = $default_source unless ($value);
231 #---- "true" authorised value
233 else {
234 push @authorised_values, qq{};
235 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
236 for my $r ( @$av ) {
237 push @authorised_values, $r->{authorised_value};
238 $authorised_lib{$r->{authorised_value}} = $r->{lib};
242 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
243 $subfield_data{marc_value} = {
244 type => 'hidden',
245 id => $subfield_data{id},
246 maxlength => $subfield_data{maxlength},
247 value => $value,
250 else {
251 $subfield_data{marc_value} = {
252 type => 'select',
253 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
254 values => \@authorised_values,
255 labels => \%authorised_lib,
256 default => $value,
260 # it's a thesaurus / authority field
261 elsif ( $subfieldlib->{authtypecode} ) {
262 $subfield_data{marc_value} = {
263 type => 'text_auth',
264 id => $subfield_data{id},
265 maxlength => $subfield_data{maxlength},
266 value => $value,
267 authtypecode => $subfieldlib->{authtypecode},
270 # it's a plugin field
271 elsif ( $subfieldlib->{value_builder} ) { # plugin
272 require Koha::FrameworkPlugin;
273 my $plugin = Koha::FrameworkPlugin->new({
274 name => $subfieldlib->{'value_builder'},
275 item_style => 1,
277 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
278 id => $subfield_data{id}, tabloop => $loop_data };
279 $plugin->build( $pars );
280 if( !$plugin->errstr ) {
281 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
282 $subfield_data{marc_value} = {
283 type => 'text_plugin',
284 id => $subfield_data{id},
285 maxlength => $subfield_data{maxlength},
286 value => $value,
287 class => $class,
288 nopopup => $plugin->noclick,
289 javascript => $plugin->javascript,
291 } else {
292 warn $plugin->errstr;
293 $subfield_data{marc_value} = {
294 type => 'text',
295 id => $subfield_data{id},
296 maxlength => $subfield_data{maxlength},
297 value => $value,
298 }; # supply default input form
301 elsif ( $tag eq '' ) { # it's an hidden field
302 $subfield_data{marc_value} = {
303 type => 'hidden',
304 id => $subfield_data{id},
305 maxlength => $subfield_data{maxlength},
306 value => $value,
309 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
310 $subfield_data{marc_value} = {
311 type => 'text',
312 id => $subfield_data{id},
313 maxlength => $subfield_data{maxlength},
314 value => $value,
317 elsif (
319 $value and length($value) > 100
321 or (
322 C4::Context->preference("marcflavour") eq "UNIMARC"
323 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
325 or (
326 C4::Context->preference("marcflavour") eq "MARC21"
327 and 500 <= $tag && $tag < 600
330 # oversize field (textarea)
331 $subfield_data{marc_value} = {
332 type => 'textarea',
333 id => $subfield_data{id},
334 value => $value,
336 } else {
337 # it's a standard field
338 $subfield_data{marc_value} = {
339 type => 'text',
340 id => $subfield_data{id},
341 maxlength => $subfield_data{maxlength},
342 value => $value,
346 # Getting list of subfields to keep when restricted editing is enabled
347 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
348 my $allowAllSubfields = (
349 not defined $subfieldsToAllowForRestrictedEditing
350 or $subfieldsToAllowForRestrictedEditing eq q||
351 ) ? 1 : 0;
352 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
354 # If we're on restricted editing, and our field is not in the list of subfields to allow,
355 # then it is read-only
356 $subfield_data{marc_value}->{readonly} = (
357 not $allowAllSubfields
358 and $restrictededition
359 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
360 ) ? 1: 0;
362 return \%subfield_data;
365 # Removes some subfields when prefilling items
366 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
367 sub removeFieldsForPrefill {
369 my $item = shift;
371 # Getting item tag
372 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
374 # Getting list of subfields to keep
375 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
377 # Removing subfields that are not in the syspref
378 if ($tag && $subfieldsToUseWhenPrefill) {
379 my $field = $item->field($tag);
380 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
381 foreach my $subfield ($field->subfields()) {
382 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
383 $field->delete_subfield(code => $subfield->[0]);
389 return $item;
393 my $input = new CGI;
394 my $error = $input->param('error');
395 my $biblionumber = $input->param('biblionumber');
396 my $itemnumber = $input->param('itemnumber');
397 my $op = $input->param('op') || q{};
398 my $hostitemnumber = $input->param('hostitemnumber');
399 my $marcflavour = C4::Context->preference("marcflavour");
400 my $searchid = $input->param('searchid');
401 # fast cataloguing datas
402 my $fa_circborrowernumber = $input->param('circborrowernumber');
403 my $fa_barcode = $input->param('barcode');
404 my $fa_branch = $input->param('branch');
405 my $fa_stickyduedate = $input->param('stickyduedate');
406 my $fa_duedatespec = $input->param('duedatespec');
408 my $frameworkcode = &GetFrameworkCode($biblionumber);
410 # Defining which userflag is needing according to the framework currently used
411 my $userflags;
412 if (defined $input->param('frameworkcode')) {
413 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
416 if (not defined $userflags) {
417 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
420 my ($template, $loggedinuser, $cookie)
421 = get_template_and_user({template_name => "cataloguing/additem.tt",
422 query => $input,
423 type => "intranet",
424 authnotrequired => 0,
425 flagsrequired => {editcatalogue => $userflags},
426 debug => 1,
430 # Does the user have a restricted item editing permission?
431 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
432 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
433 # In case user is a superlibrarian, editing is not restricted
434 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
435 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
436 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
438 my $tagslib = &GetMarcStructure(1,$frameworkcode);
439 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
441 output_and_exit_if_error( $input, $cookie, $template,
442 { module => 'cataloguing', record => $record } );
444 my $oldrecord = TransformMarcToKoha($record);
445 my $itemrecord;
446 my $nextop="additem";
447 my @errors; # store errors found while checking data BEFORE saving item.
449 # Getting last created item cookie
450 my $prefillitem = C4::Context->preference('PrefillItem');
451 my $justaddeditem;
452 my $cookieitemrecord;
453 if ($prefillitem) {
454 my $lastitemcookie = $input->cookie('LastCreatedItem');
455 if ($lastitemcookie) {
456 $lastitemcookie = uri_unescape($lastitemcookie);
457 eval {
458 if ( thaw($lastitemcookie) ) {
459 $cookieitemrecord = thaw($lastitemcookie);
460 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
463 if ($@) {
464 $lastitemcookie = 'undef' unless $lastitemcookie;
465 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
470 #-------------------------------------------------------------------------------
471 if ($op eq "additem") {
473 #-------------------------------------------------------------------------------
474 # rebuild
475 my @tags = $input->multi_param('tag');
476 my @subfields = $input->multi_param('subfield');
477 my @values = $input->multi_param('field_value');
478 # build indicator hash.
479 my @ind_tag = $input->multi_param('ind_tag');
480 my @indicator = $input->multi_param('indicator');
481 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
482 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
484 # type of add
485 my $add_submit = $input->param('add_submit');
486 my $add_duplicate_submit = $input->param('add_duplicate_submit');
487 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
488 my $number_of_copies = $input->param('number_of_copies');
490 # This is a bit tricky : if there is a cookie for the last created item and
491 # we just added an item, the cookie value is not correct yet (it will be updated
492 # next page). To prevent the form from being filled with outdated values, we
493 # force the use of "add and duplicate" feature, so the form will be filled with
494 # correct values.
495 $add_duplicate_submit = 1 if ($prefillitem);
496 $justaddeditem = 1;
498 # if autoBarcode is set to 'incremental', calculate barcode...
499 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
500 $record = _increment_barcode($record, $frameworkcode);
503 my $addedolditem = TransformMarcToKoha( $record );
505 # If we have to add or add & duplicate, we add the item
506 if ( $add_submit || $add_duplicate_submit ) {
508 # check for item barcode # being unique
509 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
510 push @errors, "barcode_not_unique" if ($exist_itemnumber);
512 # if barcode exists, don't create, but report The problem.
513 unless ($exist_itemnumber) {
514 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
515 set_item_default_location($oldbibitemnum);
517 # Pushing the last created item cookie back
518 if ($prefillitem && defined $record) {
519 my $itemcookie = $input->cookie(
520 -name => 'LastCreatedItem',
521 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
522 -value => uri_escape_utf8( freeze( $record ) ),
523 -HttpOnly => 1,
524 -expires => ''
527 $cookie = [ $cookie, $itemcookie ];
531 $nextop = "additem";
532 if ($exist_itemnumber) {
533 $itemrecord = $record;
537 # If we have to add & duplicate
538 if ($add_duplicate_submit) {
539 $itemrecord = $record;
540 if (C4::Context->preference('autoBarcode') eq 'incremental') {
541 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
543 else {
544 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
545 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
546 my $fieldItem = $itemrecord->field($tagfield);
547 $itemrecord->delete_field($fieldItem);
548 $fieldItem->delete_subfields($tagsubfield);
549 $itemrecord->insert_fields_ordered($fieldItem);
551 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
554 # If we have to add multiple copies
555 if ($add_multiple_copies_submit) {
557 use C4::Barcodes;
558 my $barcodeobj = C4::Barcodes->new;
559 my $copynumber = $addedolditem->{'copynumber'};
560 my $oldbarcode = $addedolditem->{'barcode'};
561 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
562 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
564 # If there is a barcode and we can't find their new values, we can't add multiple copies
565 my $testbarcode;
566 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
567 if ($oldbarcode && !$testbarcode) {
569 push @errors, "no_next_barcode";
570 $itemrecord = $record;
572 } else {
573 # We add each item
575 # For the first iteration
576 my $barcodevalue = $oldbarcode;
577 my $exist_itemnumber;
580 for (my $i = 0; $i < $number_of_copies;) {
582 # If there is a barcode
583 if ($barcodevalue) {
585 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
586 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
588 # Putting it into the record
589 if ($barcodevalue) {
590 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
591 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
592 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
593 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
594 # But when adding multiple copies we need to prefix it here,
595 # so we retrieve the homebranch from the item and prefix the barcode with it.
596 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
597 my $homebranch = $record->subfield($hb_field, $hb_subfield);
598 $barcodevalue = $homebranch . $barcodevalue;
600 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
603 # Checking if the barcode already exists
604 $exist_itemnumber = get_item_from_barcode($barcodevalue);
606 # Updating record with the new copynumber
607 if ( $copynumber ){
608 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
611 # Adding the item
612 if (!$exist_itemnumber) {
613 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) =
614 AddItemFromMarc( $record, $biblionumber, { skip_modzebra_update => 1 } );
615 set_item_default_location($oldbibitemnum);
617 # We count the item only if it was really added
618 # That way, all items are added, even if there was some already existing barcodes
619 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
620 $i++;
621 # Only increment copynumber if item was really added
622 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
625 # Preparing the next iteration
626 $oldbarcode = $barcodevalue;
629 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
631 undef($itemrecord);
634 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
635 print $input->redirect(
636 '/cgi-bin/koha/circ/circulation.pl?'
637 .'borrowernumber='.$fa_circborrowernumber
638 .'&barcode='.uri_escape_utf8($fa_barcode)
639 .'&duedatespec='.$fa_duedatespec
640 .'&stickyduedate=1'
642 exit;
646 #-------------------------------------------------------------------------------
647 } elsif ($op eq "edititem") {
648 #-------------------------------------------------------------------------------
649 # retrieve item if exist => then, it's a modif
650 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
651 $nextop = "saveitem";
652 #-------------------------------------------------------------------------------
653 } elsif ($op eq "dupeitem") {
654 #-------------------------------------------------------------------------------
655 # retrieve item if exist => then, it's a modif
656 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
657 if (C4::Context->preference('autoBarcode') eq 'incremental') {
658 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
660 else {
661 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
662 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
663 my $fieldItem = $itemrecord->field($tagfield);
664 $itemrecord->delete_field($fieldItem);
665 $fieldItem->delete_subfields($tagsubfield);
666 $itemrecord->insert_fields_ordered($fieldItem);
669 #check for hidden subfield and remove them for the duplicated item
670 foreach my $field ($itemrecord->fields()){
671 my $tag = $field->{_tag};
672 foreach my $subfield ($field->subfields()){
673 my $subfieldtag = $subfield->[0];
674 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
675 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
676 my $fieldItem = $itemrecord->field($tag);
677 $itemrecord->delete_field($fieldItem);
678 $fieldItem->delete_subfields($subfieldtag);
679 $itemrecord->insert_fields_ordered($fieldItem);
684 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
685 $nextop = "additem";
686 #-------------------------------------------------------------------------------
687 } elsif ($op eq "delitem") {
688 #-------------------------------------------------------------------------------
689 # check that there is no issue on this item before deletion.
690 my $item = Koha::Items->find($itemnumber);
691 $error = $item->safe_delete;
692 if(ref($error) eq 'Koha::Item'){
693 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
694 }else{
695 push @errors,$error;
696 $nextop="additem";
698 #-------------------------------------------------------------------------------
699 } elsif ($op eq "delallitems") {
700 #-------------------------------------------------------------------------------
701 my $items = Koha::Items->search({ biblionumber => $biblionumber });
702 while ( my $item = $items->next ) {
703 $error = $item->safe_delete({ skip_modzebra_update => 1 });
704 next if ref $error eq 'Koha::Item'; # Deleted item is returned if deletion successful
705 push @errors,$error;
707 C4::Biblio::ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
708 if ( @errors ) {
709 $nextop="additem";
710 } else {
711 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
712 my $views = { C4::Search::enabled_staff_search_views };
713 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
714 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
715 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
716 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
717 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
718 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
719 } else {
720 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
722 exit;
724 #-------------------------------------------------------------------------------
725 } elsif ($op eq "saveitem") {
726 #-------------------------------------------------------------------------------
727 # rebuild
728 my @tags = $input->multi_param('tag');
729 my @subfields = $input->multi_param('subfield');
730 my @values = $input->multi_param('field_value');
731 # build indicator hash.
732 my @ind_tag = $input->multi_param('ind_tag');
733 my @indicator = $input->multi_param('indicator');
734 # my $itemnumber = $input->param('itemnumber');
735 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
736 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
737 # MARC::Record builded => now, record in DB
738 # warn "R: ".$record->as_formatted;
739 # check that the barcode don't exist already
740 my $addedolditem = TransformMarcToKoha($itemtosave);
741 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
742 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
743 push @errors,"barcode_not_unique";
744 } else {
745 my $item = Koha::Items->find($itemnumber );
746 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
747 $itemnumber = q{};
748 my $olditemlost = $item->itemlost;
749 my $newitemlost = $newitem->{itemlost};
750 LostItem( $item->itemnumber, 'additem' )
751 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
753 $nextop="additem";
754 } elsif ($op eq "delinkitem"){
755 my $analyticfield = '773';
756 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
757 $analyticfield = '773';
758 } elsif ($marcflavour eq 'UNIMARC') {
759 $analyticfield = '461';
761 foreach my $field ($record->field($analyticfield)){
762 if ($field->subfield('9') eq $hostitemnumber){
763 $record->delete_field($field);
764 last;
767 my $modbibresult = ModBiblio($record, $biblionumber,'');
771 #-------------------------------------------------------------------------------
772 # build screen with existing items. and "new" one
773 #-------------------------------------------------------------------------------
775 # now, build existiing item list
776 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
777 #my @fields = $record->fields();
780 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
781 my @big_array;
782 #---- finds where items.itemnumber is stored
783 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
784 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
785 C4::Biblio::EmbedItemsInMarcBiblio({
786 marc_record => $temp,
787 biblionumber => $biblionumber });
788 my @fields = $temp->fields();
791 my @hostitemnumbers;
792 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
793 my $analyticfield = '773';
794 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
795 $analyticfield = '773';
796 } elsif ($marcflavour eq 'UNIMARC') {
797 $analyticfield = '461';
799 foreach my $hostfield ($temp->field($analyticfield)){
800 my $hostbiblionumber = $hostfield->subfield('0');
801 if ($hostbiblionumber){
802 my $hostrecord = GetMarcBiblio({
803 biblionumber => $hostbiblionumber,
804 embed_items => 1 });
805 if ($hostrecord) {
806 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
807 foreach my $hostitem ($hostrecord->field($itemfield)){
808 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
809 push (@fields, $hostitem);
810 push (@hostitemnumbers, $hostfield->subfield('9'));
818 foreach my $field (@fields) {
819 next if ( $field->tag() < 10 );
821 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
822 my %this_row;
823 # loop through each subfield
824 my $i = 0;
825 foreach my $subfield (@subf){
826 my $subfieldcode = $subfield->[0];
827 my $subfieldvalue= $subfield->[1];
829 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
830 && ($field->tag() ne $itemtagfield
831 && $subfieldcode ne $itemtagsubfield));
832 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
833 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
834 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
835 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
836 $subfieldcode, $subfieldvalue, '', $tagslib)
837 || $subfieldvalue;
840 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
841 #verifying rights
842 my $userenv = C4::Context->userenv();
843 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
844 $this_row{'nomod'} = 1;
847 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
849 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
850 foreach my $hostitemnumber (@hostitemnumbers) {
851 my $item = Koha::Items->find( $hostitemnumber );
852 if ($this_row{itemnumber} eq $hostitemnumber) {
853 $this_row{hostitemflag} = 1;
854 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
855 last;
860 if (%this_row) {
861 push(@big_array, \%this_row);
865 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
866 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
868 # now, construct template !
869 # First, the existing items for display
870 my @item_value_loop;
871 my @header_value_loop;
872 for my $row ( @big_array ) {
873 my %row_data;
874 my @item_fields;
875 foreach my $key (sort keys %witness){
876 my $item_field;
877 if ( $row->{$key} ){
878 $item_field->{field} = $row->{$key};
879 } else {
880 $item_field->{field} = '';
883 for my $kohafield (
884 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
887 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
888 next unless $key eq $subfield;
889 $item_field->{datatype} = 'date';
892 push @item_fields, $item_field;
894 $row_data{item_value} = [ @item_fields ];
895 $row_data{itemnumber} = $row->{itemnumber};
896 #reporting this_row values
897 $row_data{'nomod'} = $row->{'nomod'};
898 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
899 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
900 # $row_data{'countanalytics'} = $row->{'countanalytics'};
901 push(@item_value_loop,\%row_data);
903 foreach my $subfield_code (sort keys(%witness)) {
904 my %header_value;
905 $header_value{header_value} = $witness{$subfield_code};
907 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
908 my $kohafield = $subfieldlib->{kohafield};
909 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
910 $header_value{column_name} = $1;
913 push(@header_value_loop, \%header_value);
916 # now, build the item form for entering a new item
917 my @loop_data =();
918 my $i=0;
920 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
921 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
922 for my $library ( @$libraries ) {
923 $library->{selected} = 1 if $library->{branchcode} eq $branch
926 my $item = Koha::Items->find($itemnumber);
928 # We generate form, from actuel record
929 @fields = ();
930 if($itemrecord){
931 foreach my $field ($itemrecord->fields()){
932 my $tag = $field->{_tag};
933 foreach my $subfield ( $field->subfields() ){
935 my $subfieldtag = $subfield->[0];
936 my $value = $subfield->[1];
937 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
939 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
941 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
942 push @fields, "$tag$subfieldtag";
943 push (@loop_data, $subfield_data);
944 $i++;
949 # and now we add fields that are empty
951 # Using last created item if it exists
953 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
955 # We generate form, and fill with values if defined
956 foreach my $tag ( keys %{$tagslib}){
957 foreach my $subtag (keys %{$tagslib->{$tag}}){
958 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
959 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
960 next if any { /^$tag$subtag$/ } @fields;
962 my @values = (undef);
963 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
964 for my $value (@values){
965 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition, $item);
966 push (@loop_data, $subfield_data);
967 $i++;
971 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
973 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
974 $template->param(
975 biblionumber => $biblionumber,
976 title => $oldrecord->{title},
977 author => $oldrecord->{author},
978 item_loop => \@item_value_loop,
979 item_header_loop => \@header_value_loop,
980 item => \@loop_data,
981 itemnumber => $itemnumber,
982 barcode => $item ? $item->barcode : undef,
983 itemtagfield => $itemtagfield,
984 itemtagsubfield => $itemtagsubfield,
985 op => $nextop,
986 popup => scalar $input->param('popup') ? 1: 0,
987 C4::Search::enabled_staff_search_views,
989 $template->{'VARS'}->{'searchid'} = $searchid;
991 if ($frameworkcode eq 'FA'){
992 # fast cataloguing datas
993 $template->param(
994 'circborrowernumber' => $fa_circborrowernumber,
995 'barcode' => $fa_barcode,
996 'branch' => $fa_branch,
997 'stickyduedate' => $fa_stickyduedate,
998 'duedatespec' => $fa_duedatespec,
1002 foreach my $error (@errors) {
1003 $template->param($error => 1);
1005 output_html_with_http_headers $input, $cookie, $template->output;