Bug 10363: QA Follow-up - fixing POD and spelling
[koha.git] / cataloguing / additem.pl
blob19279b35c22866295ff47bd0c32501de0b2ceb69
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 strict;
23 #use warnings; FIXME - Bug 2505
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; # XXX subfield_is_koha_internal_p
32 use C4::Branch; # XXX subfield_is_koha_internal_p
33 use C4::ClassSource;
34 use Koha::DateUtils;
35 use List::MoreUtils qw/any/;
36 use C4::Search;
37 use Storable qw(thaw freeze);
38 use URI::Escape;
39 use C4::Members;
41 use MARC::File::XML;
42 use URI::Escape;
44 our $dbh = C4::Context->dbh;
46 sub find_value {
47 my ($tagfield,$insubfield,$record) = @_;
48 my $result;
49 my $indicator;
50 foreach my $field ($record->field($tagfield)) {
51 my @subfields = $field->subfields();
52 foreach my $subfield (@subfields) {
53 if (@$subfield[0] eq $insubfield) {
54 $result .= @$subfield[1];
55 $indicator = $field->indicator(1).$field->indicator(2);
59 return($indicator,$result);
62 sub get_item_from_barcode {
63 my ($barcode)=@_;
64 my $dbh=C4::Context->dbh;
65 my $result;
66 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
67 $rq->execute($barcode);
68 ($result)=$rq->fetchrow;
69 return($result);
72 sub set_item_default_location {
73 my $itemnumber = shift;
74 my $item = GetItem( $itemnumber );
75 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
76 $item->{'permanent_location'} = $item->{'location'};
77 $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
78 ModItem( $item, undef, $itemnumber);
80 else {
81 $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
82 ModItem( $item, undef, $itemnumber);
86 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
87 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
88 sub _increment_barcode {
89 my ($record, $frameworkcode) = @_;
90 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
91 unless ($record->field($tagfield)->subfield($tagsubfield)) {
92 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
93 $sth_barcode->execute;
94 my ($newbarcode) = $sth_barcode->fetchrow;
95 $newbarcode++;
96 # OK, we have the new barcode, now create the entry in MARC record
97 my $fieldItem = $record->field($tagfield);
98 $record->delete_field($fieldItem);
99 $fieldItem->add_subfields($tagsubfield => $newbarcode);
100 $record->insert_fields_ordered($fieldItem);
102 return $record;
106 sub generate_subfield_form {
107 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
109 my $frameworkcode = &GetFrameworkCode($biblionumber);
111 my %subfield_data;
112 my $dbh = C4::Context->dbh;
114 my $index_subfield = int(rand(1000000));
115 if ($subfieldtag eq '@'){
116 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
117 } else {
118 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
121 $subfield_data{tag} = $tag;
122 $subfield_data{subfield} = $subfieldtag;
123 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
124 $subfield_data{mandatory} = $subfieldlib->{mandatory};
125 $subfield_data{repeatable} = $subfieldlib->{repeatable};
126 $subfield_data{maxlength} = $subfieldlib->{maxlength};
128 $value =~ s/"/&quot;/g;
129 if ( ! defined( $value ) || $value eq '') {
130 $value = $subfieldlib->{defaultvalue};
131 # get today date & replace YYYY, MM, DD if provided in the default value
132 my $today_iso = output_pref( { dt=>dt_from_string, dateonly => 1, dateformat => 'iso' } );
133 my ( $year, $month, $day ) = split ('-', $today_iso);
134 $value =~ s/YYYY/$year/g;
135 $value =~ s/MM/$month/g;
136 $value =~ s/DD/$day/g;
139 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
141 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
142 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
143 my $CNtag = substr($pref_itemcallnumber, 0, 3);
144 my $CNsubfield = substr($pref_itemcallnumber, 3, 1);
145 my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
146 my $temp2 = $temp->field($CNtag);
147 if ($temp2) {
148 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
149 #remove any trailing space incase one subfield is used
150 $value =~ s/^\s+|\s+$//g;
154 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
155 my $input = new CGI;
156 $value = $input->param('barcode');
159 # Getting list of subfields to keep when restricted editing is enabled
160 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
161 my $allowAllSubfields = (
162 not defined $subfieldsToAllowForRestrictedEditing
163 or $subfieldsToAllowForRestrictedEditing == q||
164 ) ? 1 : 0;
165 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
167 if ( $subfieldlib->{authorised_value} ) {
168 my @authorised_values;
169 my %authorised_lib;
170 # builds list, depending on authorised value...
171 if ( $subfieldlib->{authorised_value} eq "branches" ) {
172 foreach my $thisbranch (@$branches) {
173 push @authorised_values, $thisbranch->{value};
174 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
175 $value = $thisbranch->{value} if $thisbranch->{selected} && !$value;
178 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
179 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
180 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
181 $sth->execute;
182 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
183 push @authorised_values, $itemtype;
184 $authorised_lib{$itemtype} = $description;
187 unless ( $value ) {
188 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
189 $itype_sth->execute( $biblionumber );
190 ( $value ) = $itype_sth->fetchrow_array;
193 #---- class_sources
195 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
196 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
198 my $class_sources = GetClassSources();
199 my $default_source = C4::Context->preference("DefaultClassificationSource");
201 foreach my $class_source (sort keys %$class_sources) {
202 next unless $class_sources->{$class_source}->{'used'} or
203 ($value and $class_source eq $value) or
204 ($class_source eq $default_source);
205 push @authorised_values, $class_source;
206 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
208 $value = $default_source unless ($value);
210 #---- "true" authorised value
212 else {
213 push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
214 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
215 for my $r ( @$av ) {
216 push @authorised_values, $r->{authorised_value};
217 $authorised_lib{$r->{authorised_value}} = $r->{lib};
221 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
222 $subfield_data{marc_value} = {
223 type => 'hidden',
224 id => $subfield_data{id},
225 maxlength => $subfield_data{max_length},
226 value => $value,
229 else {
230 $subfield_data{marc_value} = {
231 type => 'select',
232 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
233 values => \@authorised_values,
234 labels => \%authorised_lib,
235 default => $value,
237 # If we're on restricted editing, and our field is not in the list of subfields to allow,
238 # then it is read-only
239 $subfield_data{marc_value}->{readonlyselect} = (
240 not $allowAllSubfields
241 and $restrictededition
242 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
243 ) ? 1: 0;
246 # it's a thesaurus / authority field
247 elsif ( $subfieldlib->{authtypecode} ) {
248 $subfield_data{marc_value} = {
249 type => 'text_auth',
250 id => $subfield_data{id},
251 maxlength => $subfield_data{max_length},
252 value => $value,
253 authtypecode => $subfieldlib->{authtypecode},
256 # it's a plugin field
257 elsif ( $subfieldlib->{value_builder} ) { # plugin
258 require Koha::FrameworkPlugin;
259 my $plugin = Koha::FrameworkPlugin->new({
260 name => $subfieldlib->{'value_builder'},
261 item_style => 1,
263 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
264 id => $subfield_data{id}, tabloop => $loop_data };
265 $plugin->build( $pars );
266 if( !$plugin->errstr ) {
267 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
268 $subfield_data{marc_value} = {
269 type => 'text_plugin',
270 id => $subfield_data{id},
271 maxlength => $subfield_data{max_length},
272 value => $value,
273 class => $class,
274 nopopup => $plugin->noclick,
275 javascript => $plugin->javascript,
277 } else {
278 warn $plugin->errstr;
279 $subfield_data{marc_value} = {
280 type => 'text',
281 id => $subfield_data{id},
282 maxlength => $subfield_data{max_length},
283 value => $value,
284 }; # supply default input form
287 elsif ( $tag eq '' ) { # it's an hidden field
288 $subfield_data{marc_value} = {
289 type => 'hidden',
290 id => $subfield_data{id},
291 maxlength => $subfield_data{max_length},
292 value => $value,
295 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
296 $subfield_data{marc_value} = {
297 type => 'text',
298 id => $subfield_data{id},
299 maxlength => $subfield_data{max_length},
300 value => $value,
303 elsif (
304 length($value) > 100
305 or (
306 C4::Context->preference("marcflavour") eq "UNIMARC"
307 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
309 or (
310 C4::Context->preference("marcflavour") eq "MARC21"
311 and 500 <= $tag && $tag < 600
314 # oversize field (textarea)
315 $subfield_data{marc_value} = {
316 type => 'textarea',
317 id => $subfield_data{id},
318 value => $value,
320 } else {
321 # it's a standard field
322 $subfield_data{marc_value} = {
323 type => 'text',
324 id => $subfield_data{id},
325 maxlength => $subfield_data{max_length},
326 value => $value,
330 return \%subfield_data;
333 # Removes some subfields when prefilling items
334 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
335 sub removeFieldsForPrefill {
337 my $item = shift;
339 # Getting item tag
340 my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
342 # Getting list of subfields to keep
343 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
345 # Removing subfields that are not in the syspref
346 if ($tag && $subfieldsToUseWhenPrefill) {
347 my $field = $item->field($tag);
348 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
349 foreach my $subfield ($field->subfields()) {
350 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
351 $field->delete_subfield(code => $subfield->[0]);
357 return $item;
361 my $input = new CGI;
362 my $error = $input->param('error');
363 my $biblionumber = $input->param('biblionumber');
364 my $itemnumber = $input->param('itemnumber');
365 my $op = $input->param('op');
366 my $hostitemnumber = $input->param('hostitemnumber');
367 my $marcflavour = C4::Context->preference("marcflavour");
368 my $searchid = $input->param('searchid');
369 # fast cataloguing datas
370 my $fa_circborrowernumber = $input->param('circborrowernumber');
371 my $fa_barcode = $input->param('barcode');
372 my $fa_branch = $input->param('branch');
373 my $fa_stickyduedate = $input->param('stickyduedate');
374 my $fa_duedatespec = $input->param('duedatespec');
376 my $frameworkcode = &GetFrameworkCode($biblionumber);
378 # Defining which userflag is needing according to the framework currently used
379 my $userflags;
380 if (defined $input->param('frameworkcode')) {
381 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
384 if (not defined $userflags) {
385 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
388 my ($template, $loggedinuser, $cookie)
389 = get_template_and_user({template_name => "cataloguing/additem.tt",
390 query => $input,
391 type => "intranet",
392 authnotrequired => 0,
393 flagsrequired => {editcatalogue => $userflags},
394 debug => 1,
398 # Does the user have a restricted item editing permission?
399 my $uid = $loggedinuser ? GetMember( borrowernumber => $loggedinuser )->{userid} : undef;
400 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
401 # In case user is a superlibrarian, editing is not restricted
402 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
403 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
404 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
406 my $tagslib = &GetMarcStructure(1,$frameworkcode);
407 my $record = GetMarcBiblio($biblionumber);
408 my $oldrecord = TransformMarcToKoha($dbh,$record);
409 my $itemrecord;
410 my $nextop="additem";
411 my @errors; # store errors found while checking data BEFORE saving item.
413 # Getting last created item cookie
414 my $prefillitem = C4::Context->preference('PrefillItem');
415 my $justaddeditem;
416 my $cookieitemrecord;
417 if ($prefillitem) {
418 my $lastitemcookie = $input->cookie('LastCreatedItem');
419 if ($lastitemcookie) {
420 $lastitemcookie = uri_unescape($lastitemcookie);
421 if ( thaw($lastitemcookie) ) {
422 $cookieitemrecord = thaw($lastitemcookie) ;
423 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
428 #-------------------------------------------------------------------------------
429 if ($op eq "additem") {
431 #-------------------------------------------------------------------------------
432 # rebuild
433 my @tags = $input->param('tag');
434 my @subfields = $input->param('subfield');
435 my @values = $input->param('field_value');
436 # build indicator hash.
437 my @ind_tag = $input->param('ind_tag');
438 my @indicator = $input->param('indicator');
439 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
440 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
442 # type of add
443 my $add_submit = $input->param('add_submit');
444 my $add_duplicate_submit = $input->param('add_duplicate_submit');
445 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
446 my $number_of_copies = $input->param('number_of_copies');
448 # This is a bit tricky : if there is a cookie for the last created item and
449 # we just added an item, the cookie value is not correct yet (it will be updated
450 # next page). To prevent the form from being filled with outdated values, we
451 # force the use of "add and duplicate" feature, so the form will be filled with
452 # correct values.
453 $add_duplicate_submit = 1 if ($prefillitem);
454 $justaddeditem = 1;
456 # if autoBarcode is set to 'incremental', calculate barcode...
457 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
458 $record = _increment_barcode($record, $frameworkcode);
461 my $addedolditem = TransformMarcToKoha( $dbh, $record );
463 # If we have to add or add & duplicate, we add the item
464 if ( $add_submit || $add_duplicate_submit ) {
466 # check for item barcode # being unique
467 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
468 push @errors, "barcode_not_unique" if ($exist_itemnumber);
470 # if barcode exists, don't create, but report The problem.
471 unless ($exist_itemnumber) {
472 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
473 set_item_default_location($oldbibitemnum);
475 # Pushing the last created item cookie back
476 if ($prefillitem && defined $record) {
477 my $itemcookie = $input->cookie(
478 -name => 'LastCreatedItem',
479 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
480 -value => uri_escape_utf8( freeze( $record ) ),
481 -HttpOnly => 1,
482 -expires => ''
485 $cookie = [ $cookie, $itemcookie ];
489 $nextop = "additem";
490 if ($exist_itemnumber) {
491 $itemrecord = $record;
495 # If we have to add & duplicate
496 if ($add_duplicate_submit) {
497 $itemrecord = $record;
498 if (C4::Context->preference('autoBarcode') eq 'incremental') {
499 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
501 else {
502 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
503 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
504 my $fieldItem = $itemrecord->field($tagfield);
505 $itemrecord->delete_field($fieldItem);
506 $fieldItem->delete_subfields($tagsubfield);
507 $itemrecord->insert_fields_ordered($fieldItem);
509 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
512 # If we have to add multiple copies
513 if ($add_multiple_copies_submit) {
515 use C4::Barcodes;
516 my $barcodeobj = C4::Barcodes->new;
517 my $oldbarcode = $addedolditem->{'barcode'};
518 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
520 # If there is a barcode and we can't find him new values, we can't add multiple copies
521 my $testbarcode;
522 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
523 if ($oldbarcode && !$testbarcode) {
525 push @errors, "no_next_barcode";
526 $itemrecord = $record;
528 } else {
529 # We add each item
531 # For the first iteration
532 my $barcodevalue = $oldbarcode;
533 my $exist_itemnumber;
536 for (my $i = 0; $i < $number_of_copies;) {
538 # If there is a barcode
539 if ($barcodevalue) {
541 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
542 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
544 # Putting it into the record
545 if ($barcodevalue) {
546 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
549 # Checking if the barcode already exists
550 $exist_itemnumber = get_item_from_barcode($barcodevalue);
553 # Adding the item
554 if (!$exist_itemnumber) {
555 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
556 set_item_default_location($oldbibitemnum);
558 # We count the item only if it was really added
559 # That way, all items are added, even if there was some already existing barcodes
560 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
561 $i++;
564 # Preparing the next iteration
565 $oldbarcode = $barcodevalue;
567 undef($itemrecord);
570 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
571 print $input->redirect(
572 '/cgi-bin/koha/circ/circulation.pl?'
573 .'borrowernumber='.$fa_circborrowernumber
574 .'&barcode='.uri_escape_utf8($fa_barcode)
575 .'&duedatespec='.$fa_duedatespec
576 .'&stickyduedate=1'
578 exit;
582 #-------------------------------------------------------------------------------
583 } elsif ($op eq "edititem") {
584 #-------------------------------------------------------------------------------
585 # retrieve item if exist => then, it's a modif
586 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
587 $nextop = "saveitem";
588 #-------------------------------------------------------------------------------
589 } elsif ($op eq "delitem") {
590 #-------------------------------------------------------------------------------
591 # check that there is no issue on this item before deletion.
592 $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
593 if($error == 1){
594 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
595 }else{
596 push @errors,$error;
597 $nextop="additem";
599 #-------------------------------------------------------------------------------
600 } elsif ($op eq "delallitems") {
601 #-------------------------------------------------------------------------------
602 my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
603 my $errortest=0;
604 my $itemfail;
605 foreach my $biblioitem (@biblioitems) {
606 my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
608 foreach my $item (@$items) {
609 $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
610 $itemfail =$item;
611 if($error == 1){
612 next
614 else {
615 push @errors,$error;
616 $errortest++
619 if($errortest > 0){
620 $nextop="additem";
622 else {
623 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
624 my $views = { C4::Search::enabled_staff_search_views };
625 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
626 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
627 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
628 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
629 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
630 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
631 } else {
632 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
634 exit;
637 #-------------------------------------------------------------------------------
638 } elsif ($op eq "saveitem") {
639 #-------------------------------------------------------------------------------
640 # rebuild
641 my @tags = $input->param('tag');
642 my @subfields = $input->param('subfield');
643 my @values = $input->param('field_value');
644 # build indicator hash.
645 my @ind_tag = $input->param('ind_tag');
646 my @indicator = $input->param('indicator');
647 # my $itemnumber = $input->param('itemnumber');
648 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
649 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
650 # MARC::Record builded => now, record in DB
651 # warn "R: ".$record->as_formatted;
652 # check that the barcode don't exist already
653 my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
654 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
655 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
656 push @errors,"barcode_not_unique";
657 } else {
658 ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
659 $itemnumber="";
661 my $item = GetItem( $itemnumber );
662 my $olditemlost = $item->{'itemlost'};
664 my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
666 my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
667 if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
668 LostItem($itemnumber,'MARK RETURNED');
670 $nextop="additem";
671 } elsif ($op eq "delinkitem"){
672 my $analyticfield = '773';
673 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
674 $analyticfield = '773';
675 } elsif ($marcflavour eq 'UNIMARC') {
676 $analyticfield = '461';
678 foreach my $field ($record->field($analyticfield)){
679 if ($field->subfield('9') eq $hostitemnumber){
680 $record->delete_field($field);
681 last;
684 my $modbibresult = ModBiblio($record, $biblionumber,'');
688 #-------------------------------------------------------------------------------
689 # build screen with existing items. and "new" one
690 #-------------------------------------------------------------------------------
692 # now, build existiing item list
693 my $temp = GetMarcBiblio( $biblionumber );
694 #my @fields = $record->fields();
697 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
698 my @big_array;
699 #---- finds where items.itemnumber is stored
700 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
701 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
702 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
703 my @fields = $temp->fields();
706 my @hostitemnumbers;
707 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
708 my $analyticfield = '773';
709 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
710 $analyticfield = '773';
711 } elsif ($marcflavour eq 'UNIMARC') {
712 $analyticfield = '461';
714 foreach my $hostfield ($temp->field($analyticfield)){
715 my $hostbiblionumber = $hostfield->subfield('0');
716 if ($hostbiblionumber){
717 my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
718 if ($hostrecord) {
719 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
720 foreach my $hostitem ($hostrecord->field($itemfield)){
721 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
722 push (@fields, $hostitem);
723 push (@hostitemnumbers, $hostfield->subfield('9'));
732 foreach my $field (@fields) {
733 next if ( $field->tag() < 10 );
735 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
736 my %this_row;
737 # loop through each subfield
738 my $i = 0;
739 foreach my $subfield (@subf){
740 my $subfieldcode = $subfield->[0];
741 my $subfieldvalue= $subfield->[1];
743 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
744 && ($field->tag() ne $itemtagfield
745 && $subfieldcode ne $itemtagsubfield));
746 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
747 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
748 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
749 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
750 $subfieldcode, $subfieldvalue, '', $tagslib)
751 || $subfieldvalue;
754 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
755 #verifying rights
756 my $userenv = C4::Context->userenv();
757 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
758 $this_row{'nomod'} = 1;
761 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
763 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
764 foreach my $hostitemnumber (@hostitemnumbers){
765 if ($this_row{itemnumber} eq $hostitemnumber){
766 $this_row{hostitemflag} = 1;
767 $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
768 last;
772 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
773 # if ($countanalytics > 0){
774 # $this_row{countanalytics} = $countanalytics;
779 if (%this_row) {
780 push(@big_array, \%this_row);
784 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
785 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
787 # now, construct template !
788 # First, the existing items for display
789 my @item_value_loop;
790 my @header_value_loop;
791 for my $row ( @big_array ) {
792 my %row_data;
793 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
794 $row_data{item_value} = [ @item_fields ];
795 $row_data{itemnumber} = $row->{itemnumber};
796 #reporting this_row values
797 $row_data{'nomod'} = $row->{'nomod'};
798 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
799 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
800 # $row_data{'countanalytics'} = $row->{'countanalytics'};
801 push(@item_value_loop,\%row_data);
803 foreach my $subfield_code (sort keys(%witness)) {
804 my %header_value;
805 $header_value{header_value} = $witness{$subfield_code};
807 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
808 my $kohafield = $subfieldlib->{kohafield};
809 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
810 $header_value{column_name} = $1;
813 push(@header_value_loop, \%header_value);
816 # now, build the item form for entering a new item
817 my @loop_data =();
818 my $i=0;
820 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
822 my $onlymine =
823 C4::Context->preference('IndependentBranches')
824 && C4::Context->userenv
825 && !C4::Context->IsSuperLibrarian()
826 && C4::Context->userenv->{branch};
827 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
828 my $branches = GetBranchesLoop($branch,$onlymine); # build once ahead of time, instead of multiple times later.
830 # We generate form, from actuel record
831 @fields = ();
832 if($itemrecord){
833 foreach my $field ($itemrecord->fields()){
834 my $tag = $field->{_tag};
835 foreach my $subfield ( $field->subfields() ){
837 my $subfieldtag = $subfield->[0];
838 my $value = $subfield->[1];
839 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
841 next if subfield_is_koha_internal_p($subfieldtag);
842 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
844 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
845 push @fields, "$tag$subfieldtag";
846 push (@loop_data, $subfield_data);
847 $i++;
852 # and now we add fields that are empty
854 # Using last created item if it exists
856 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
858 # We generate form, and fill with values if defined
859 foreach my $tag ( keys %{$tagslib}){
860 foreach my $subtag (keys %{$tagslib->{$tag}}){
861 next if subfield_is_koha_internal_p($subtag);
862 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
863 next if any { /^$tag$subtag$/ } @fields;
865 my @values = (undef);
866 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
867 for my $value (@values){
868 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
869 push (@loop_data, $subfield_data);
870 $i++;
874 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
876 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
877 $template->param(
878 biblionumber => $biblionumber,
879 title => $oldrecord->{title},
880 author => $oldrecord->{author},
881 item_loop => \@item_value_loop,
882 item_header_loop => \@header_value_loop,
883 item => \@loop_data,
884 itemnumber => $itemnumber,
885 barcode => GetBarcodeFromItemnumber($itemnumber),
886 itemtagfield => $itemtagfield,
887 itemtagsubfield => $itemtagsubfield,
888 op => $nextop,
889 opisadd => ($nextop eq "saveitem") ? 0 : 1,
890 popup => $input->param('popup') ? 1: 0,
891 C4::Search::enabled_staff_search_views,
893 $template->{'VARS'}->{'searchid'} = $searchid;
895 if ($frameworkcode eq 'FA'){
896 # fast cataloguing datas
897 $template->param(
898 'circborrowernumber' => $fa_circborrowernumber,
899 'barcode' => $fa_barcode,
900 'branch' => $fa_branch,
901 'stickyduedate' => $fa_stickyduedate,
902 'duedatespec' => $fa_duedatespec,
906 foreach my $error (@errors) {
907 $template->param($error => 1);
909 output_html_with_http_headers $input, $cookie, $template->output;