BUG 7143: Add Kyle Hall as the 42nd developer to history
[koha.git] / cataloguing / additem.pl
blobd127179f92d6f3ae10cad4219fec87132ec0bcef
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 under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 C4::Dates;
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, $today_iso, $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{random} = int(rand(1000000)); # why do we need 2 different randoms?
124 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
125 $subfield_data{mandatory} = $subfieldlib->{mandatory};
126 $subfield_data{repeatable} = $subfieldlib->{repeatable};
127 $subfield_data{maxlength} = $subfieldlib->{maxlength};
129 $value =~ s/"/&quot;/g;
130 if ( ! defined( $value ) || $value eq '') {
131 $value = $subfieldlib->{defaultvalue};
132 # get today date & replace YYYY, MM, DD if provided in the default value
133 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
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');
158 my $attributes_no_value = qq(id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$subfield_data{maxlength}" );
159 my $attributes_no_value_textarea = qq(id="$subfield_data{id}" name="field_value" class="input_marceditor" rows="5" cols="64" );
161 # Getting list of subfields to keep when restricted editing is enabled
162 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
163 my $allowAllSubfields = (
164 not defined $subfieldsToAllowForRestrictedEditing
165 or $subfieldsToAllowForRestrictedEditing == q||
166 ) ? 1 : 0;
167 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
169 # If we're on restricted editing, and our field is not in the list of subfields to allow,
170 # then it is read-only
171 $attributes_no_value .= 'readonly="readonly" '
172 if (
173 not $allowAllSubfields
174 and $restrictededition
175 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
178 my $attributes = qq($attributes_no_value value="$value" );
180 if ( $subfieldlib->{authorised_value} ) {
181 my @authorised_values;
182 my %authorised_lib;
183 # builds list, depending on authorised value...
184 if ( $subfieldlib->{authorised_value} eq "branches" ) {
185 foreach my $thisbranch (@$branches) {
186 push @authorised_values, $thisbranch->{value};
187 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
188 $value = $thisbranch->{value} if $thisbranch->{selected} && !$value;
191 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
192 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
193 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
194 $sth->execute;
195 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
196 push @authorised_values, $itemtype;
197 $authorised_lib{$itemtype} = $description;
200 unless ( $value ) {
201 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
202 $itype_sth->execute( $biblionumber );
203 ( $value ) = $itype_sth->fetchrow_array;
206 #---- class_sources
208 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
209 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
211 my $class_sources = GetClassSources();
212 my $default_source = C4::Context->preference("DefaultClassificationSource");
214 foreach my $class_source (sort keys %$class_sources) {
215 next unless $class_sources->{$class_source}->{'used'} or
216 ($value and $class_source eq $value) or
217 ($class_source eq $default_source);
218 push @authorised_values, $class_source;
219 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
221 $value = $default_source unless ($value);
223 #---- "true" authorised value
225 else {
226 push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
227 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
228 for my $r ( @$av ) {
229 push @authorised_values, $r->{authorised_value};
230 $authorised_lib{$r->{authorised_value}} = $r->{lib};
234 if ($subfieldlib->{'hidden'}) {
235 $subfield_data{marc_value} = qq(<input type="hidden" $attributes /> $authorised_lib{$value});
237 else {
238 my @scrparam = (
239 -name => "field_value",
240 -values => \@authorised_values,
241 -default => $value,
242 -labels => \%authorised_lib,
243 -override => 1,
244 -size => 1,
245 -multiple => 0,
246 -id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
247 -class => "input_marceditor",
250 # If we're on restricted editing, and our field is not in the list of subfields to allow,
251 # then it is read-only
252 push @scrparam, (-readonly => "readonly"), (-disabled => "disabled")
253 if (
254 not $allowAllSubfields
255 and $restrictededition
256 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
258 $subfield_data{marc_value} =CGI::scrolling_list(@scrparam);
262 # it's a thesaurus / authority field
263 elsif ( $subfieldlib->{authtypecode} ) {
264 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
265 <a href=\"#\" class=\"buttonDot\"
266 onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$subfieldlib->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
269 # it's a plugin field
270 elsif ( $subfieldlib->{value_builder} ) {
271 # opening plugin
272 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $subfieldlib->{'value_builder'};
273 if (do $plugin) {
274 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
275 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
276 my $change = index($javascript, 'function Change') > -1 ?
277 "return Change$function_name($subfield_data{random}, '$subfield_data{id}');" :
278 'return 1;';
279 $subfield_data{marc_value} = qq[<input type="text" $attributes
280 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
281 onchange=" $change"
282 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
283 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
284 $javascript];
285 } else {
286 warn "Plugin Failed: $plugin";
287 $subfield_data{marc_value} = "<input type=\"text\" $attributes />"; # supply default input form
290 elsif ( $tag eq '' ) { # it's an hidden field
291 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
293 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
294 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
296 elsif ( length($value) > 100
297 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
298 300 <= $tag && $tag < 400 && $subfieldtag eq 'a' )
299 or (C4::Context->preference("marcflavour") eq "MARC21" and
300 500 <= $tag && $tag < 600 )
302 # oversize field (textarea)
303 $subfield_data{marc_value} = "<textarea $attributes_no_value_textarea>$value</textarea>\n";
304 } else {
305 # it's a standard field
306 $subfield_data{marc_value} = "<input type=\"text\" $attributes />";
309 return \%subfield_data;
312 # Removes some subfields when prefilling items
313 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
314 sub removeFieldsForPrefill {
316 my $item = shift;
318 # Getting item tag
319 my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
321 # Getting list of subfields to keep
322 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
324 # Removing subfields that are not in the syspref
325 if ($tag && $subfieldsToUseWhenPrefill) {
326 my $field = $item->field($tag);
327 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
328 foreach my $subfield ($field->subfields()) {
329 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
330 $field->delete_subfield(code => $subfield->[0]);
336 return $item;
340 my $input = new CGI;
341 my $error = $input->param('error');
342 my $biblionumber = $input->param('biblionumber');
343 my $itemnumber = $input->param('itemnumber');
344 my $op = $input->param('op');
345 my $hostitemnumber = $input->param('hostitemnumber');
346 my $marcflavour = C4::Context->preference("marcflavour");
347 my $searchid = $input->param('searchid');
348 # fast cataloguing datas
349 my $fa_circborrowernumber = $input->param('circborrowernumber');
350 my $fa_barcode = $input->param('barcode');
351 my $fa_branch = $input->param('branch');
352 my $fa_stickyduedate = $input->param('stickyduedate');
353 my $fa_duedatespec = $input->param('duedatespec');
355 my $frameworkcode = &GetFrameworkCode($biblionumber);
357 # Defining which userflag is needing according to the framework currently used
358 my $userflags;
359 if (defined $input->param('frameworkcode')) {
360 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
363 if (not defined $userflags) {
364 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
367 my ($template, $loggedinuser, $cookie)
368 = get_template_and_user({template_name => "cataloguing/additem.tt",
369 query => $input,
370 type => "intranet",
371 authnotrequired => 0,
372 flagsrequired => {editcatalogue => $userflags},
373 debug => 1,
377 # Does the user have a restricted item editing permission?
378 my $uid = $loggedinuser ? GetMember( borrowernumber => $loggedinuser )->{userid} : undef;
379 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
380 # In case user is a superlibrarian, editing is not restricted
381 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
382 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
383 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
385 my $today_iso = C4::Dates->today('iso');
386 my $tagslib = &GetMarcStructure(1,$frameworkcode);
387 my $record = GetMarcBiblio($biblionumber);
388 my $oldrecord = TransformMarcToKoha($dbh,$record);
389 my $itemrecord;
390 my $nextop="additem";
391 my @errors; # store errors found while checking data BEFORE saving item.
393 # Getting last created item cookie
394 my $prefillitem = C4::Context->preference('PrefillItem');
395 my $justaddeditem;
396 my $cookieitemrecord;
397 if ($prefillitem) {
398 my $lastitemcookie = $input->cookie('LastCreatedItem');
399 if ($lastitemcookie) {
400 $lastitemcookie = uri_unescape($lastitemcookie);
401 if ( thaw($lastitemcookie) ) {
402 $cookieitemrecord = thaw($lastitemcookie) ;
403 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
408 #-------------------------------------------------------------------------------
409 if ($op eq "additem") {
411 #-------------------------------------------------------------------------------
412 # rebuild
413 my @tags = $input->param('tag');
414 my @subfields = $input->param('subfield');
415 my @values = $input->param('field_value');
416 # build indicator hash.
417 my @ind_tag = $input->param('ind_tag');
418 my @indicator = $input->param('indicator');
419 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
420 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
422 # type of add
423 my $add_submit = $input->param('add_submit');
424 my $add_duplicate_submit = $input->param('add_duplicate_submit');
425 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
426 my $number_of_copies = $input->param('number_of_copies');
428 # This is a bit tricky : if there is a cookie for the last created item and
429 # we just added an item, the cookie value is not correct yet (it will be updated
430 # next page). To prevent the form from being filled with outdated values, we
431 # force the use of "add and duplicate" feature, so the form will be filled with
432 # correct values.
433 $add_duplicate_submit = 1 if ($prefillitem);
434 $justaddeditem = 1;
436 # if autoBarcode is set to 'incremental', calculate barcode...
437 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
438 $record = _increment_barcode($record, $frameworkcode);
441 my $addedolditem = TransformMarcToKoha( $dbh, $record );
443 # If we have to add or add & duplicate, we add the item
444 if ( $add_submit || $add_duplicate_submit ) {
446 # check for item barcode # being unique
447 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
448 push @errors, "barcode_not_unique" if ($exist_itemnumber);
450 # if barcode exists, don't create, but report The problem.
451 unless ($exist_itemnumber) {
452 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
453 set_item_default_location($oldbibitemnum);
455 # Pushing the last created item cookie back
456 if ($prefillitem && defined $record) {
457 my $itemcookie = $input->cookie(
458 -name => 'LastCreatedItem',
459 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
460 -value => uri_escape_utf8( freeze( $record ) ),
461 -HttpOnly => 1,
462 -expires => ''
465 $cookie = [ $cookie, $itemcookie ];
469 $nextop = "additem";
470 if ($exist_itemnumber) {
471 $itemrecord = $record;
475 # If we have to add & duplicate
476 if ($add_duplicate_submit) {
477 $itemrecord = $record;
478 if (C4::Context->preference('autoBarcode') eq 'incremental') {
479 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
481 else {
482 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
483 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
484 my $fieldItem = $itemrecord->field($tagfield);
485 $itemrecord->delete_field($fieldItem);
486 $fieldItem->delete_subfields($tagsubfield);
487 $itemrecord->insert_fields_ordered($fieldItem);
489 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
492 # If we have to add multiple copies
493 if ($add_multiple_copies_submit) {
495 use C4::Barcodes;
496 my $barcodeobj = C4::Barcodes->new;
497 my $oldbarcode = $addedolditem->{'barcode'};
498 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
500 # If there is a barcode and we can't find him new values, we can't add multiple copies
501 my $testbarcode;
502 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
503 if ($oldbarcode && !$testbarcode) {
505 push @errors, "no_next_barcode";
506 $itemrecord = $record;
508 } else {
509 # We add each item
511 # For the first iteration
512 my $barcodevalue = $oldbarcode;
513 my $exist_itemnumber;
516 for (my $i = 0; $i < $number_of_copies;) {
518 # If there is a barcode
519 if ($barcodevalue) {
521 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
522 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
524 # Putting it into the record
525 if ($barcodevalue) {
526 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
529 # Checking if the barcode already exists
530 $exist_itemnumber = get_item_from_barcode($barcodevalue);
533 # Adding the item
534 if (!$exist_itemnumber) {
535 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
536 set_item_default_location($oldbibitemnum);
538 # We count the item only if it was really added
539 # That way, all items are added, even if there was some already existing barcodes
540 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
541 $i++;
544 # Preparing the next iteration
545 $oldbarcode = $barcodevalue;
547 undef($itemrecord);
550 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
551 print $input->redirect(
552 '/cgi-bin/koha/circ/circulation.pl?'
553 .'borrowernumber='.$fa_circborrowernumber
554 .'&barcode='.uri_escape_utf8($fa_barcode)
555 .'&duedatespec='.$fa_duedatespec
556 .'&stickyduedate=1'
558 exit;
562 #-------------------------------------------------------------------------------
563 } elsif ($op eq "edititem") {
564 #-------------------------------------------------------------------------------
565 # retrieve item if exist => then, it's a modif
566 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
567 $nextop = "saveitem";
568 #-------------------------------------------------------------------------------
569 } elsif ($op eq "delitem") {
570 #-------------------------------------------------------------------------------
571 # check that there is no issue on this item before deletion.
572 $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
573 if($error == 1){
574 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
575 }else{
576 push @errors,$error;
577 $nextop="additem";
579 #-------------------------------------------------------------------------------
580 } elsif ($op eq "delallitems") {
581 #-------------------------------------------------------------------------------
582 my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
583 my $errortest=0;
584 my $itemfail;
585 foreach my $biblioitem (@biblioitems) {
586 my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
588 foreach my $item (@$items) {
589 $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
590 $itemfail =$item;
591 if($error == 1){
592 next
594 else {
595 push @errors,$error;
596 $errortest++
599 if($errortest > 0){
600 $nextop="additem";
602 else {
603 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
604 my $views = { C4::Search::enabled_staff_search_views };
605 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
606 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
607 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
608 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
609 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
610 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
611 } else {
612 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
614 exit;
617 #-------------------------------------------------------------------------------
618 } elsif ($op eq "saveitem") {
619 #-------------------------------------------------------------------------------
620 # rebuild
621 my @tags = $input->param('tag');
622 my @subfields = $input->param('subfield');
623 my @values = $input->param('field_value');
624 # build indicator hash.
625 my @ind_tag = $input->param('ind_tag');
626 my @indicator = $input->param('indicator');
627 # my $itemnumber = $input->param('itemnumber');
628 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
629 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
630 # MARC::Record builded => now, record in DB
631 # warn "R: ".$record->as_formatted;
632 # check that the barcode don't exist already
633 my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
634 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
635 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
636 push @errors,"barcode_not_unique";
637 } else {
638 ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
639 $itemnumber="";
641 my $item = GetItem( $itemnumber );
642 my $olditemlost = $item->{'itemlost'};
644 my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
646 my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
647 if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
648 LostItem($itemnumber,'MARK RETURNED');
650 $nextop="additem";
651 } elsif ($op eq "delinkitem"){
652 my $analyticfield = '773';
653 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
654 $analyticfield = '773';
655 } elsif ($marcflavour eq 'UNIMARC') {
656 $analyticfield = '461';
658 foreach my $field ($record->field($analyticfield)){
659 if ($field->subfield('9') eq $hostitemnumber){
660 $record->delete_field($field);
661 last;
664 my $modbibresult = ModBiblio($record, $biblionumber,'');
668 #-------------------------------------------------------------------------------
669 # build screen with existing items. and "new" one
670 #-------------------------------------------------------------------------------
672 # now, build existiing item list
673 my $temp = GetMarcBiblio( $biblionumber );
674 #my @fields = $record->fields();
677 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
678 my @big_array;
679 #---- finds where items.itemnumber is stored
680 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
681 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
682 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
683 my @fields = $temp->fields();
686 my @hostitemnumbers;
687 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
688 my $analyticfield = '773';
689 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
690 $analyticfield = '773';
691 } elsif ($marcflavour eq 'UNIMARC') {
692 $analyticfield = '461';
694 foreach my $hostfield ($temp->field($analyticfield)){
695 my $hostbiblionumber = $hostfield->subfield('0');
696 if ($hostbiblionumber){
697 my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
698 if ($hostrecord) {
699 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
700 foreach my $hostitem ($hostrecord->field($itemfield)){
701 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
702 push (@fields, $hostitem);
703 push (@hostitemnumbers, $hostfield->subfield('9'));
712 foreach my $field (@fields) {
713 next if ( $field->tag() < 10 );
715 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
716 my %this_row;
717 # loop through each subfield
718 my $i = 0;
719 foreach my $subfield (@subf){
720 my $subfieldcode = $subfield->[0];
721 my $subfieldvalue= $subfield->[1];
723 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
724 && ($field->tag() ne $itemtagfield
725 && $subfieldcode ne $itemtagsubfield));
726 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
727 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
728 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
729 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
730 $subfieldcode, $subfieldvalue, '', $tagslib)
731 || $subfieldvalue;
734 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
735 #verifying rights
736 my $userenv = C4::Context->userenv();
737 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
738 $this_row{'nomod'} = 1;
741 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
743 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
744 foreach my $hostitemnumber (@hostitemnumbers){
745 if ($this_row{itemnumber} eq $hostitemnumber){
746 $this_row{hostitemflag} = 1;
747 $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
748 last;
752 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
753 # if ($countanalytics > 0){
754 # $this_row{countanalytics} = $countanalytics;
759 if (%this_row) {
760 push(@big_array, \%this_row);
764 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
765 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
767 # now, construct template !
768 # First, the existing items for display
769 my @item_value_loop;
770 my @header_value_loop;
771 for my $row ( @big_array ) {
772 my %row_data;
773 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
774 $row_data{item_value} = [ @item_fields ];
775 $row_data{itemnumber} = $row->{itemnumber};
776 #reporting this_row values
777 $row_data{'nomod'} = $row->{'nomod'};
778 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
779 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
780 # $row_data{'countanalytics'} = $row->{'countanalytics'};
781 push(@item_value_loop,\%row_data);
783 foreach my $subfield_code (sort keys(%witness)) {
784 my %header_value;
785 $header_value{header_value} = $witness{$subfield_code};
786 push(@header_value_loop, \%header_value);
789 # now, build the item form for entering a new item
790 my @loop_data =();
791 my $i=0;
793 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
795 my $onlymine =
796 C4::Context->preference('IndependentBranches')
797 && C4::Context->userenv
798 && !C4::Context->IsSuperLibrarian()
799 && C4::Context->userenv->{branch};
800 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
801 my $branches = GetBranchesLoop($branch,$onlymine); # build once ahead of time, instead of multiple times later.
803 # We generate form, from actuel record
804 @fields = ();
805 if($itemrecord){
806 foreach my $field ($itemrecord->fields()){
807 my $tag = $field->{_tag};
808 foreach my $subfield ( $field->subfields() ){
810 my $subfieldtag = $subfield->[0];
811 my $value = $subfield->[1];
812 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
814 next if subfield_is_koha_internal_p($subfieldtag);
815 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
817 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
818 push @fields, "$tag$subfieldtag";
819 push (@loop_data, $subfield_data);
820 $i++;
825 # and now we add fields that are empty
827 # Using last created item if it exists
829 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
831 # We generate form, and fill with values if defined
832 foreach my $tag ( keys %{$tagslib}){
833 foreach my $subtag (keys %{$tagslib->{$tag}}){
834 next if subfield_is_koha_internal_p($subtag);
835 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
836 next if any { /^$tag$subtag$/ } @fields;
838 my @values = (undef);
839 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
840 for my $value (@values){
841 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
842 push (@loop_data, $subfield_data);
843 $i++;
847 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
849 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
850 $template->param(
851 biblionumber => $biblionumber,
852 title => $oldrecord->{title},
853 author => $oldrecord->{author},
854 item_loop => \@item_value_loop,
855 item_header_loop => \@header_value_loop,
856 item => \@loop_data,
857 itemnumber => $itemnumber,
858 barcode => GetBarcodeFromItemnumber($itemnumber),
859 itemtagfield => $itemtagfield,
860 itemtagsubfield => $itemtagsubfield,
861 op => $nextop,
862 opisadd => ($nextop eq "saveitem") ? 0 : 1,
863 popup => $input->param('popup') ? 1: 0,
864 C4::Search::enabled_staff_search_views,
866 $template->{'VARS'}->{'searchid'} = $searchid;
868 if ($frameworkcode eq 'FA'){
869 # fast cataloguing datas
870 $template->param(
871 'circborrowernumber' => $fa_circborrowernumber,
872 'barcode' => $fa_barcode,
873 'branch' => $fa_branch,
874 'stickyduedate' => $fa_stickyduedate,
875 'duedatespec' => $fa_duedatespec,
879 foreach my $error (@errors) {
880 $template->param($error => 1);
882 output_html_with_http_headers $input, $cookie, $template->output;