Bug 12879: Remove unnecesary diags from Holds.t
[koha.git] / cataloguing / additem.pl
blob7110f7f30d42f4f3b2d735c20d19c667f59f8eed
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;
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;
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) = @_;
109 my $frameworkcode = &GetFrameworkCode($biblionumber);
110 my %subfield_data;
111 my $dbh = C4::Context->dbh;
113 my $index_subfield = int(rand(1000000));
114 if ($subfieldtag eq '@'){
115 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
116 } else {
117 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
120 $subfield_data{tag} = $tag;
121 $subfield_data{subfield} = $subfieldtag;
122 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
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 ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
133 $value =~ s/YYYY/$year/g;
134 $value =~ s/MM/$month/g;
135 $value =~ s/DD/$day/g;
138 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} < -4));
140 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
141 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
142 my $CNtag = substr($pref_itemcallnumber, 0, 3);
143 my $CNsubfield = substr($pref_itemcallnumber, 3, 1);
144 my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
145 my $temp2 = $temp->field($CNtag);
146 if ($temp2) {
147 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
148 #remove any trailing space incase one subfield is used
149 $value =~ s/^\s+|\s+$//g;
153 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
154 my $input = new CGI;
155 $value = $input->param('barcode');
157 my $attributes_no_value = qq(id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$subfield_data{maxlength}" );
158 my $attributes_no_value_textarea = qq(id="$subfield_data{id}" name="field_value" class="input_marceditor" rows="5" cols="64" );
159 my $attributes = qq($attributes_no_value value="$value" );
161 if ( $subfieldlib->{authorised_value} ) {
162 my @authorised_values;
163 my %authorised_lib;
164 # builds list, depending on authorised value...
165 if ( $subfieldlib->{authorised_value} eq "branches" ) {
166 foreach my $thisbranch (@$branches) {
167 push @authorised_values, $thisbranch->{value};
168 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
169 $value = $thisbranch->{value} if $thisbranch->{selected} && !$value;
172 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
173 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
174 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
175 $sth->execute;
176 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
177 push @authorised_values, $itemtype;
178 $authorised_lib{$itemtype} = $description;
181 unless ( $value ) {
182 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
183 $itype_sth->execute( $biblionumber );
184 ( $value ) = $itype_sth->fetchrow_array;
187 #---- class_sources
189 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
190 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
192 my $class_sources = GetClassSources();
193 my $default_source = C4::Context->preference("DefaultClassificationSource");
195 foreach my $class_source (sort keys %$class_sources) {
196 next unless $class_sources->{$class_source}->{'used'} or
197 ($value and $class_source eq $value) or
198 ($class_source eq $default_source);
199 push @authorised_values, $class_source;
200 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
202 $value = $default_source unless ($value);
204 #---- "true" authorised value
206 else {
207 push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
208 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
209 for my $r ( @$av ) {
210 push @authorised_values, $r->{authorised_value};
211 $authorised_lib{$r->{authorised_value}} = $r->{lib};
215 if ($subfieldlib->{'hidden'}) {
216 $subfield_data{marc_value} = qq(<input type="hidden" $attributes /> $authorised_lib{$value});
218 else {
219 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
220 -name => "field_value",
221 -values => \@authorised_values,
222 -default => $value,
223 -labels => \%authorised_lib,
224 -override => 1,
225 -size => 1,
226 -multiple => 0,
227 -id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
228 -class => "input_marceditor",
233 # it's a thesaurus / authority field
234 elsif ( $subfieldlib->{authtypecode} ) {
235 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
236 <a href=\"#\" class=\"buttonDot\"
237 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>
240 # it's a plugin field
241 elsif ( $subfieldlib->{value_builder} ) {
242 # opening plugin
243 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $subfieldlib->{'value_builder'};
244 if (do $plugin) {
245 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
246 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
247 my $change = index($javascript, 'function Change') > -1 ?
248 "return Change$function_name($subfield_data{random}, '$subfield_data{id}');" :
249 'return 1;';
250 $subfield_data{marc_value} = qq[<input type="text" $attributes
251 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
252 onchange=" $change"
253 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
254 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
255 $javascript];
256 } else {
257 warn "Plugin Failed: $plugin";
258 $subfield_data{marc_value} = "<input type=\"text\" $attributes />"; # supply default input form
261 elsif ( $tag eq '' ) { # it's an hidden field
262 $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
264 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
265 $subfield_data{marc_value} = qq(<input type="text" $attributes />);
267 elsif ( length($value) > 100
268 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
269 300 <= $tag && $tag < 400 && $subfieldtag eq 'a' )
270 or (C4::Context->preference("marcflavour") eq "MARC21" and
271 500 <= $tag && $tag < 600 )
273 # oversize field (textarea)
274 $subfield_data{marc_value} = "<textarea $attributes_no_value_textarea>$value</textarea>\n";
275 } else {
276 # it's a standard field
277 $subfield_data{marc_value} = "<input type=\"text\" $attributes />";
280 return \%subfield_data;
283 # Removes some subfields when prefilling items
284 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
285 sub removeFieldsForPrefill {
287 my $item = shift;
289 # Getting item tag
290 my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
292 # Getting list of subfields to keep
293 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
295 # Removing subfields that are not in the syspref
296 if ($tag && $subfieldsToUseWhenPrefill) {
297 my $field = $item->field($tag);
298 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
299 foreach my $subfield ($field->subfields()) {
300 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
301 $field->delete_subfield(code => $subfield->[0]);
307 return $item;
311 my $input = new CGI;
312 my $error = $input->param('error');
313 my $biblionumber = $input->param('biblionumber');
314 my $itemnumber = $input->param('itemnumber');
315 my $op = $input->param('op');
316 my $hostitemnumber = $input->param('hostitemnumber');
317 my $marcflavour = C4::Context->preference("marcflavour");
318 my $searchid = $input->param('searchid');
319 # fast cataloguing datas
320 my $fa_circborrowernumber = $input->param('circborrowernumber');
321 my $fa_barcode = $input->param('barcode');
322 my $fa_branch = $input->param('branch');
323 my $fa_stickyduedate = $input->param('stickyduedate');
324 my $fa_duedatespec = $input->param('duedatespec');
326 my $frameworkcode = &GetFrameworkCode($biblionumber);
328 # Defining which userflag is needing according to the framework currently used
329 my $userflags;
330 if (defined $input->param('frameworkcode')) {
331 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
334 if (not defined $userflags) {
335 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
338 my ($template, $loggedinuser, $cookie)
339 = get_template_and_user({template_name => "cataloguing/additem.tt",
340 query => $input,
341 type => "intranet",
342 authnotrequired => 0,
343 flagsrequired => {editcatalogue => $userflags},
344 debug => 1,
348 my $today_iso = C4::Dates->today('iso');
349 my $tagslib = &GetMarcStructure(1,$frameworkcode);
350 my $record = GetMarcBiblio($biblionumber);
351 my $oldrecord = TransformMarcToKoha($dbh,$record);
352 my $itemrecord;
353 my $nextop="additem";
354 my @errors; # store errors found while checking data BEFORE saving item.
356 # Getting last created item cookie
357 my $prefillitem = C4::Context->preference('PrefillItem');
358 my $justaddeditem;
359 my $cookieitemrecord;
360 if ($prefillitem) {
361 my $lastitemcookie = $input->cookie('LastCreatedItem');
362 if ($lastitemcookie) {
363 $lastitemcookie = uri_unescape($lastitemcookie);
364 if ( thaw($lastitemcookie) ) {
365 $cookieitemrecord = thaw($lastitemcookie) ;
366 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
371 #-------------------------------------------------------------------------------
372 if ($op eq "additem") {
374 #-------------------------------------------------------------------------------
375 # rebuild
376 my @tags = $input->param('tag');
377 my @subfields = $input->param('subfield');
378 my @values = $input->param('field_value');
379 # build indicator hash.
380 my @ind_tag = $input->param('ind_tag');
381 my @indicator = $input->param('indicator');
382 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
383 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
385 # type of add
386 my $add_submit = $input->param('add_submit');
387 my $add_duplicate_submit = $input->param('add_duplicate_submit');
388 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
389 my $number_of_copies = $input->param('number_of_copies');
391 # This is a bit tricky : if there is a cookie for the last created item and
392 # we just added an item, the cookie value is not correct yet (it will be updated
393 # next page). To prevent the form from being filled with outdated values, we
394 # force the use of "add and duplicate" feature, so the form will be filled with
395 # correct values.
396 $add_duplicate_submit = 1 if ($prefillitem);
397 $justaddeditem = 1;
399 # if autoBarcode is set to 'incremental', calculate barcode...
400 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
401 $record = _increment_barcode($record, $frameworkcode);
404 my $addedolditem = TransformMarcToKoha( $dbh, $record );
406 # If we have to add or add & duplicate, we add the item
407 if ( $add_submit || $add_duplicate_submit ) {
409 # check for item barcode # being unique
410 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
411 push @errors, "barcode_not_unique" if ($exist_itemnumber);
413 # if barcode exists, don't create, but report The problem.
414 unless ($exist_itemnumber) {
415 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
416 set_item_default_location($oldbibitemnum);
418 # Pushing the last created item cookie back
419 if ($prefillitem && defined $record) {
420 my $itemcookie = $input->cookie(
421 -name => 'LastCreatedItem',
422 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
423 -value => uri_escape_utf8( freeze( $record ) ),
424 -HttpOnly => 1,
425 -expires => ''
428 $cookie = [ $cookie, $itemcookie ];
432 $nextop = "additem";
433 if ($exist_itemnumber) {
434 $itemrecord = $record;
438 # If we have to add & duplicate
439 if ($add_duplicate_submit) {
440 $itemrecord = $record;
441 if (C4::Context->preference('autoBarcode') eq 'incremental') {
442 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
444 else {
445 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
446 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
447 my $fieldItem = $itemrecord->field($tagfield);
448 $itemrecord->delete_field($fieldItem);
449 $fieldItem->delete_subfields($tagsubfield);
450 $itemrecord->insert_fields_ordered($fieldItem);
452 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
455 # If we have to add multiple copies
456 if ($add_multiple_copies_submit) {
458 use C4::Barcodes;
459 my $barcodeobj = C4::Barcodes->new;
460 my $oldbarcode = $addedolditem->{'barcode'};
461 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
463 # If there is a barcode and we can't find him new values, we can't add multiple copies
464 my $testbarcode;
465 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
466 if ($oldbarcode && !$testbarcode) {
468 push @errors, "no_next_barcode";
469 $itemrecord = $record;
471 } else {
472 # We add each item
474 # For the first iteration
475 my $barcodevalue = $oldbarcode;
476 my $exist_itemnumber;
479 for (my $i = 0; $i < $number_of_copies;) {
481 # If there is a barcode
482 if ($barcodevalue) {
484 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
485 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
487 # Putting it into the record
488 if ($barcodevalue) {
489 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
492 # Checking if the barcode already exists
493 $exist_itemnumber = get_item_from_barcode($barcodevalue);
496 # Adding the item
497 if (!$exist_itemnumber) {
498 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
499 set_item_default_location($oldbibitemnum);
501 # We count the item only if it was really added
502 # That way, all items are added, even if there was some already existing barcodes
503 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
504 $i++;
507 # Preparing the next iteration
508 $oldbarcode = $barcodevalue;
510 undef($itemrecord);
513 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
514 print $input->redirect(
515 '/cgi-bin/koha/circ/circulation.pl?'
516 .'borrowernumber='.$fa_circborrowernumber
517 .'&barcode='.uri_escape($fa_barcode)
518 .'&duedatespec='.$fa_duedatespec
519 .'&stickyduedate=1'
521 exit;
525 #-------------------------------------------------------------------------------
526 } elsif ($op eq "edititem") {
527 #-------------------------------------------------------------------------------
528 # retrieve item if exist => then, it's a modif
529 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
530 $nextop = "saveitem";
531 #-------------------------------------------------------------------------------
532 } elsif ($op eq "delitem") {
533 #-------------------------------------------------------------------------------
534 # check that there is no issue on this item before deletion.
535 $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
536 if($error == 1){
537 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
538 }else{
539 push @errors,$error;
540 $nextop="additem";
542 #-------------------------------------------------------------------------------
543 } elsif ($op eq "delallitems") {
544 #-------------------------------------------------------------------------------
545 my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
546 my $errortest=0;
547 my $itemfail;
548 foreach my $biblioitem (@biblioitems) {
549 my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
551 foreach my $item (@$items) {
552 $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
553 $itemfail =$item;
554 if($error == 1){
555 next
557 else {
558 push @errors,$error;
559 $errortest++
562 if($errortest > 0){
563 $nextop="additem";
565 else {
566 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
567 my $views = { C4::Search::enabled_staff_search_views };
568 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
569 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
570 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
571 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
572 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
573 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
574 } else {
575 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
577 exit;
580 #-------------------------------------------------------------------------------
581 } elsif ($op eq "saveitem") {
582 #-------------------------------------------------------------------------------
583 # rebuild
584 my @tags = $input->param('tag');
585 my @subfields = $input->param('subfield');
586 my @values = $input->param('field_value');
587 # build indicator hash.
588 my @ind_tag = $input->param('ind_tag');
589 my @indicator = $input->param('indicator');
590 # my $itemnumber = $input->param('itemnumber');
591 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
592 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
593 # MARC::Record builded => now, record in DB
594 # warn "R: ".$record->as_formatted;
595 # check that the barcode don't exist already
596 my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
597 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
598 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
599 push @errors,"barcode_not_unique";
600 } else {
601 ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
602 $itemnumber="";
604 my $item = GetItem( $itemnumber );
605 my $olditemlost = $item->{'itemlost'};
607 my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
609 my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
610 if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
611 LostItem($itemnumber,'MARK RETURNED');
613 $nextop="additem";
614 } elsif ($op eq "delinkitem"){
615 my $analyticfield = '773';
616 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
617 $analyticfield = '773';
618 } elsif ($marcflavour eq 'UNIMARC') {
619 $analyticfield = '461';
621 foreach my $field ($record->field($analyticfield)){
622 if ($field->subfield('9') eq $hostitemnumber){
623 $record->delete_field($field);
624 last;
627 my $modbibresult = ModBiblio($record, $biblionumber,'');
631 #-------------------------------------------------------------------------------
632 # build screen with existing items. and "new" one
633 #-------------------------------------------------------------------------------
635 # now, build existiing item list
636 my $temp = GetMarcBiblio( $biblionumber );
637 #my @fields = $record->fields();
640 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
641 my @big_array;
642 #---- finds where items.itemnumber is stored
643 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
644 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
645 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
646 my @fields = $temp->fields();
649 my @hostitemnumbers;
650 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
651 my $analyticfield = '773';
652 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
653 $analyticfield = '773';
654 } elsif ($marcflavour eq 'UNIMARC') {
655 $analyticfield = '461';
657 foreach my $hostfield ($temp->field($analyticfield)){
658 my $hostbiblionumber = $hostfield->subfield('0');
659 if ($hostbiblionumber){
660 my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
661 if ($hostrecord) {
662 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
663 foreach my $hostitem ($hostrecord->field($itemfield)){
664 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
665 push (@fields, $hostitem);
666 push (@hostitemnumbers, $hostfield->subfield('9'));
675 foreach my $field (@fields) {
676 next if ( $field->tag() < 10 );
678 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
679 my %this_row;
680 # loop through each subfield
681 my $i = 0;
682 foreach my $subfield (@subf){
683 my $subfieldcode = $subfield->[0];
684 my $subfieldvalue= $subfield->[1];
686 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
687 && ($field->tag() ne $itemtagfield
688 && $subfieldcode ne $itemtagsubfield));
689 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
690 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
691 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
692 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
693 $subfieldcode, $subfieldvalue, '', $tagslib)
694 || $subfieldvalue;
697 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
698 #verifying rights
699 my $userenv = C4::Context->userenv();
700 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
701 $this_row{'nomod'} = 1;
704 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
706 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
707 foreach my $hostitemnumber (@hostitemnumbers){
708 if ($this_row{itemnumber} eq $hostitemnumber){
709 $this_row{hostitemflag} = 1;
710 $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
711 last;
715 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
716 # if ($countanalytics > 0){
717 # $this_row{countanalytics} = $countanalytics;
722 if (%this_row) {
723 push(@big_array, \%this_row);
727 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
728 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
730 # now, construct template !
731 # First, the existing items for display
732 my @item_value_loop;
733 my @header_value_loop;
734 for my $row ( @big_array ) {
735 my %row_data;
736 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
737 $row_data{item_value} = [ @item_fields ];
738 $row_data{itemnumber} = $row->{itemnumber};
739 #reporting this_row values
740 $row_data{'nomod'} = $row->{'nomod'};
741 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
742 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
743 # $row_data{'countanalytics'} = $row->{'countanalytics'};
744 push(@item_value_loop,\%row_data);
746 foreach my $subfield_code (sort keys(%witness)) {
747 my %header_value;
748 $header_value{header_value} = $witness{$subfield_code};
749 push(@header_value_loop, \%header_value);
752 # now, build the item form for entering a new item
753 my @loop_data =();
754 my $i=0;
756 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
758 my $onlymine =
759 C4::Context->preference('IndependentBranches')
760 && C4::Context->userenv
761 && !C4::Context->IsSuperLibrarian()
762 && C4::Context->userenv->{branch};
763 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
764 my $branches = GetBranchesLoop($branch,$onlymine); # build once ahead of time, instead of multiple times later.
766 # We generate form, from actuel record
767 @fields = ();
768 if($itemrecord){
769 foreach my $field ($itemrecord->fields()){
770 my $tag = $field->{_tag};
771 foreach my $subfield ( $field->subfields() ){
773 my $subfieldtag = $subfield->[0];
774 my $value = $subfield->[1];
775 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
777 next if subfield_is_koha_internal_p($subfieldtag);
778 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
780 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);
782 push @fields, "$tag$subfieldtag";
783 push (@loop_data, $subfield_data);
784 $i++;
789 # and now we add fields that are empty
791 # Using last created item if it exists
793 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
795 # We generate form, and fill with values if defined
796 foreach my $tag ( keys %{$tagslib}){
797 foreach my $subtag (keys %{$tagslib->{$tag}}){
798 next if subfield_is_koha_internal_p($subtag);
799 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
800 next if any { /^$tag$subtag$/ } @fields;
802 my @values = (undef);
803 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
804 for my $value (@values){
805 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);
806 push (@loop_data, $subfield_data);
807 $i++;
811 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
813 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
814 $template->param( title => $record->title() ) if ($record ne "-1");
815 $template->param(
816 biblionumber => $biblionumber,
817 title => $oldrecord->{title},
818 author => $oldrecord->{author},
819 item_loop => \@item_value_loop,
820 item_header_loop => \@header_value_loop,
821 item => \@loop_data,
822 itemnumber => $itemnumber,
823 barcode => GetBarcodeFromItemnumber($itemnumber),
824 itemtagfield => $itemtagfield,
825 itemtagsubfield => $itemtagsubfield,
826 op => $nextop,
827 opisadd => ($nextop eq "saveitem") ? 0 : 1,
828 popup => $input->param('popup') ? 1: 0,
829 C4::Search::enabled_staff_search_views,
831 $template->{'VARS'}->{'searchid'} = $searchid;
833 if ($frameworkcode eq 'FA'){
834 # fast cataloguing datas
835 $template->param(
836 'circborrowernumber' => $fa_circborrowernumber,
837 'barcode' => $fa_barcode,
838 'branch' => $fa_branch,
839 'stickyduedate' => $fa_stickyduedate,
840 'duedatespec' => $fa_duedatespec,
844 foreach my $error (@errors) {
845 $template->param($error => 1);
847 output_html_with_http_headers $input, $cookie, $template->output;