Bug 3134: (follow-up) improve ID and peport name sorting on saved reports page
[koha.git] / cataloguing / additem.pl
blobf2a5ccbec9a8f509a8858ecb8012196c76896b4e
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::Koha; # XXX subfield_is_koha_internal_p
31 use C4::Branch; # XXX subfield_is_koha_internal_p
32 use C4::ClassSource;
33 use C4::Dates;
34 use List::MoreUtils qw/any/;
35 use C4::Search;
36 use Storable qw(thaw freeze);
37 use URI::Escape;
40 use MARC::File::XML;
41 use URI::Escape;
43 our $dbh = C4::Context->dbh;
45 sub find_value {
46 my ($tagfield,$insubfield,$record) = @_;
47 my $result;
48 my $indicator;
49 foreach my $field ($record->field($tagfield)) {
50 my @subfields = $field->subfields();
51 foreach my $subfield (@subfields) {
52 if (@$subfield[0] eq $insubfield) {
53 $result .= @$subfield[1];
54 $indicator = $field->indicator(1).$field->indicator(2);
58 return($indicator,$result);
61 sub get_item_from_barcode {
62 my ($barcode)=@_;
63 my $dbh=C4::Context->dbh;
64 my $result;
65 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
66 $rq->execute($barcode);
67 ($result)=$rq->fetchrow;
68 return($result);
71 sub set_item_default_location {
72 my $itemnumber = shift;
73 my $item = GetItem( $itemnumber );
74 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
75 $item->{'permanent_location'} = $item->{'location'};
76 $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
77 ModItem( $item, undef, $itemnumber);
79 else {
80 $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
81 ModItem( $item, undef, $itemnumber);
85 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
86 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
87 sub _increment_barcode {
88 my ($record, $frameworkcode) = @_;
89 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
90 unless ($record->field($tagfield)->subfield($tagsubfield)) {
91 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
92 $sth_barcode->execute;
93 my ($newbarcode) = $sth_barcode->fetchrow;
94 $newbarcode++;
95 # OK, we have the new barcode, now create the entry in MARC record
96 my $fieldItem = $record->field($tagfield);
97 $record->delete_field($fieldItem);
98 $fieldItem->add_subfields($tagsubfield => $newbarcode);
99 $record->insert_fields_ordered($fieldItem);
101 return $record;
105 sub generate_subfield_form {
106 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $today_iso, $biblionumber, $temp, $loop_data, $i) = @_;
108 my $frameworkcode = &GetFrameworkCode($biblionumber);
109 my %subfield_data;
110 my $dbh = C4::Context->dbh;
112 my $index_subfield = int(rand(1000000));
113 if ($subfieldtag eq '@'){
114 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
115 } else {
116 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
119 $subfield_data{tag} = $tag;
120 $subfield_data{subfield} = $subfieldtag;
121 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
122 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
123 $subfield_data{mandatory} = $subfieldlib->{mandatory};
124 $subfield_data{repeatable} = $subfieldlib->{repeatable};
125 $subfield_data{maxlength} = $subfieldlib->{maxlength};
127 $value =~ s/"/&quot;/g;
128 if ( ! defined( $value ) || $value eq '') {
129 $value = $subfieldlib->{defaultvalue};
130 # get today date & replace YYYY, MM, DD if provided in the default value
131 my ( $year, $month, $day ) = split ',', $today_iso; # FIXME: iso dates don't have commas!
132 $value =~ s/YYYY/$year/g;
133 $value =~ s/MM/$month/g;
134 $value =~ s/DD/$day/g;
137 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} < -4));
139 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
140 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
141 my $CNtag = substr($pref_itemcallnumber, 0, 3);
142 my $CNsubfield = substr($pref_itemcallnumber, 3, 1);
143 my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
144 my $temp2 = $temp->field($CNtag);
145 if ($temp2) {
146 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
147 #remove any trailing space incase one subfield is used
148 $value =~ s/^\s+|\s+$//g;
152 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
153 my $input = new CGI;
154 $value = $input->param('barcode');
156 my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="$subfield_data{maxlength}" );
157 my $attributes_no_value_textarea = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" rows="5" cols="64" );
158 my $attributes = qq($attributes_no_value value="$value" );
160 if ( $subfieldlib->{authorised_value} ) {
161 my @authorised_values;
162 my %authorised_lib;
163 # builds list, depending on authorised value...
164 if ( $subfieldlib->{authorised_value} eq "branches" ) {
165 foreach my $thisbranch (@$branches) {
166 push @authorised_values, $thisbranch->{value};
167 $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
168 $value = $thisbranch->{value} if $thisbranch->{selected} && !$value;
171 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
172 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
173 my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
174 $sth->execute;
175 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
176 push @authorised_values, $itemtype;
177 $authorised_lib{$itemtype} = $description;
180 unless ( $value ) {
181 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
182 $itype_sth->execute( $biblionumber );
183 ( $value ) = $itype_sth->fetchrow_array;
186 #---- class_sources
188 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
189 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
191 my $class_sources = GetClassSources();
192 my $default_source = C4::Context->preference("DefaultClassificationSource");
194 foreach my $class_source (sort keys %$class_sources) {
195 next unless $class_sources->{$class_source}->{'used'} or
196 ($value and $class_source eq $value) or
197 ($class_source eq $default_source);
198 push @authorised_values, $class_source;
199 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
201 $value = $default_source unless ($value);
203 #---- "true" authorised value
205 else {
206 push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
207 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
208 for my $r ( @$av ) {
209 push @authorised_values, $r->{authorised_value};
210 $authorised_lib{$r->{authorised_value}} = $r->{lib};
214 if ($subfieldlib->{'hidden'}) {
215 $subfield_data{marc_value} = qq(<input type="hidden" $attributes /> $authorised_lib{$value});
217 else {
218 $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
219 -name => "field_value",
220 -values => \@authorised_values,
221 -default => $value,
222 -labels => \%authorised_lib,
223 -override => 1,
224 -size => 1,
225 -multiple => 0,
226 -tabindex => 1,
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);
405 if (C4::Context->preference('autoBarcode') eq 'incremental') {
406 $record = _increment_barcode($record, $frameworkcode);
409 my $addedolditem = TransformMarcToKoha( $dbh, $record );
411 # If we have to add or add & duplicate, we add the item
412 if ( $add_submit || $add_duplicate_submit ) {
414 # check for item barcode # being unique
415 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
416 push @errors, "barcode_not_unique" if ($exist_itemnumber);
418 # if barcode exists, don't create, but report The problem.
419 unless ($exist_itemnumber) {
420 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
421 set_item_default_location($oldbibitemnum);
423 # Pushing the last created item cookie back
424 if ($prefillitem && defined $record) {
425 my $itemcookie = $input->cookie(
426 -name => 'LastCreatedItem',
427 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
428 -value => uri_escape_utf8( freeze( $record ) ),
429 -HttpOnly => 1,
430 -expires => ''
433 $cookie = [ $cookie, $itemcookie ];
437 $nextop = "additem";
438 if ($exist_itemnumber) {
439 $itemrecord = $record;
443 # If we have to add & duplicate
444 if ($add_duplicate_submit) {
445 $itemrecord = $record;
446 if (C4::Context->preference('autoBarcode') eq 'incremental') {
447 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
449 else {
450 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
451 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
452 my $fieldItem = $itemrecord->field($tagfield);
453 $itemrecord->delete_field($fieldItem);
454 $fieldItem->delete_subfields($tagsubfield);
455 $itemrecord->insert_fields_ordered($fieldItem);
457 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
460 # If we have to add multiple copies
461 if ($add_multiple_copies_submit) {
463 use C4::Barcodes;
464 my $barcodeobj = C4::Barcodes->new;
465 my $oldbarcode = $addedolditem->{'barcode'};
466 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
468 # If there is a barcode and we can't find him new values, we can't add multiple copies
469 my $testbarcode;
470 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
471 if ($oldbarcode && !$testbarcode) {
473 push @errors, "no_next_barcode";
474 $itemrecord = $record;
476 } else {
477 # We add each item
479 # For the first iteration
480 my $barcodevalue = $oldbarcode;
481 my $exist_itemnumber;
484 for (my $i = 0; $i < $number_of_copies;) {
486 # If there is a barcode
487 if ($barcodevalue) {
489 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
490 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
492 # Putting it into the record
493 if ($barcodevalue) {
494 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
497 # Checking if the barcode already exists
498 $exist_itemnumber = get_item_from_barcode($barcodevalue);
501 # Adding the item
502 if (!$exist_itemnumber) {
503 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
504 set_item_default_location($oldbibitemnum);
506 # We count the item only if it was really added
507 # That way, all items are added, even if there was some already existing barcodes
508 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
509 $i++;
512 # Preparing the next iteration
513 $oldbarcode = $barcodevalue;
515 undef($itemrecord);
518 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
519 print $input->redirect(
520 '/cgi-bin/koha/circ/circulation.pl?'
521 .'borrowernumber='.$fa_circborrowernumber
522 .'&barcode='.uri_escape($fa_barcode)
523 .'&duedatespec='.$fa_duedatespec
524 .'&stickyduedate=1'
526 exit;
530 #-------------------------------------------------------------------------------
531 } elsif ($op eq "edititem") {
532 #-------------------------------------------------------------------------------
533 # retrieve item if exist => then, it's a modif
534 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
535 $nextop = "saveitem";
536 #-------------------------------------------------------------------------------
537 } elsif ($op eq "delitem") {
538 #-------------------------------------------------------------------------------
539 # check that there is no issue on this item before deletion.
540 $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
541 if($error == 1){
542 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
543 }else{
544 push @errors,$error;
545 $nextop="additem";
547 #-------------------------------------------------------------------------------
548 } elsif ($op eq "delallitems") {
549 #-------------------------------------------------------------------------------
550 my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
551 my $errortest=0;
552 my $itemfail;
553 foreach my $biblioitem (@biblioitems) {
554 my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
556 foreach my $item (@$items) {
557 $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
558 $itemfail =$item;
559 if($error == 1){
560 next
562 else {
563 push @errors,$error;
564 $errortest++
567 if($errortest > 0){
568 $nextop="additem";
570 else {
571 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
572 my $views = { C4::Search::enabled_staff_search_views };
573 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
574 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
575 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
576 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
577 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
578 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
579 } else {
580 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
582 exit;
585 #-------------------------------------------------------------------------------
586 } elsif ($op eq "saveitem") {
587 #-------------------------------------------------------------------------------
588 # rebuild
589 my @tags = $input->param('tag');
590 my @subfields = $input->param('subfield');
591 my @values = $input->param('field_value');
592 # build indicator hash.
593 my @ind_tag = $input->param('ind_tag');
594 my @indicator = $input->param('indicator');
595 # my $itemnumber = $input->param('itemnumber');
596 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
597 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
598 # MARC::Record builded => now, record in DB
599 # warn "R: ".$record->as_formatted;
600 # check that the barcode don't exist already
601 my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
602 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
603 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
604 push @errors,"barcode_not_unique";
605 } else {
606 ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
607 $itemnumber="";
609 $nextop="additem";
610 } elsif ($op eq "delinkitem"){
611 my $analyticfield = '773';
612 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
613 $analyticfield = '773';
614 } elsif ($marcflavour eq 'UNIMARC') {
615 $analyticfield = '461';
617 foreach my $field ($record->field($analyticfield)){
618 if ($field->subfield('9') eq $hostitemnumber){
619 $record->delete_field($field);
620 last;
623 my $modbibresult = ModBiblio($record, $biblionumber,'');
627 #-------------------------------------------------------------------------------
628 # build screen with existing items. and "new" one
629 #-------------------------------------------------------------------------------
631 # now, build existiing item list
632 my $temp = GetMarcBiblio( $biblionumber );
633 #my @fields = $record->fields();
636 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
637 my @big_array;
638 #---- finds where items.itemnumber is stored
639 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
640 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
641 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
642 my @fields = $temp->fields();
645 my @hostitemnumbers;
646 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
647 my $analyticfield = '773';
648 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
649 $analyticfield = '773';
650 } elsif ($marcflavour eq 'UNIMARC') {
651 $analyticfield = '461';
653 foreach my $hostfield ($temp->field($analyticfield)){
654 my $hostbiblionumber = $hostfield->subfield('0');
655 if ($hostbiblionumber){
656 my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
657 if ($hostrecord) {
658 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
659 foreach my $hostitem ($hostrecord->field($itemfield)){
660 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
661 push (@fields, $hostitem);
662 push (@hostitemnumbers, $hostfield->subfield('9'));
671 foreach my $field (@fields) {
672 next if ( $field->tag() < 10 );
674 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
675 my %this_row;
676 # loop through each subfield
677 my $i = 0;
678 foreach my $subfield (@subf){
679 my $subfieldcode = $subfield->[0];
680 my $subfieldvalue= $subfield->[1];
682 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
683 && ($field->tag() ne $itemtagfield
684 && $subfieldcode ne $itemtagsubfield));
685 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
686 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
687 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
688 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
689 $subfieldcode, $subfieldvalue, '', $tagslib)
690 || $subfieldvalue;
693 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
694 #verifying rights
695 my $userenv = C4::Context->userenv();
696 unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subfieldvalue))){
697 $this_row{'nomod'} = 1;
700 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
702 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
703 foreach my $hostitemnumber (@hostitemnumbers){
704 if ($this_row{itemnumber} eq $hostitemnumber){
705 $this_row{hostitemflag} = 1;
706 $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
707 last;
711 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
712 # if ($countanalytics > 0){
713 # $this_row{countanalytics} = $countanalytics;
718 if (%this_row) {
719 push(@big_array, \%this_row);
723 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
724 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
726 # now, construct template !
727 # First, the existing items for display
728 my @item_value_loop;
729 my @header_value_loop;
730 for my $row ( @big_array ) {
731 my %row_data;
732 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
733 $row_data{item_value} = [ @item_fields ];
734 $row_data{itemnumber} = $row->{itemnumber};
735 #reporting this_row values
736 $row_data{'nomod'} = $row->{'nomod'};
737 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
738 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
739 # $row_data{'countanalytics'} = $row->{'countanalytics'};
740 push(@item_value_loop,\%row_data);
742 foreach my $subfield_code (sort keys(%witness)) {
743 my %header_value;
744 $header_value{header_value} = $witness{$subfield_code};
745 push(@header_value_loop, \%header_value);
748 # now, build the item form for entering a new item
749 my @loop_data =();
750 my $i=0;
752 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
754 my $onlymine = C4::Context->preference('IndependentBranches') &&
755 C4::Context->userenv &&
756 C4::Context->userenv->{flags}!=1 &&
757 C4::Context->userenv->{branch};
758 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
759 my $branches = GetBranchesLoop($branch,$onlymine); # build once ahead of time, instead of multiple times later.
761 # We generate form, from actuel record
762 @fields = ();
763 if($itemrecord){
764 foreach my $field ($itemrecord->fields()){
765 my $tag = $field->{_tag};
766 foreach my $subfield ( $field->subfields() ){
768 my $subfieldtag = $subfield->[0];
769 my $value = $subfield->[1];
770 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
772 next if subfield_is_koha_internal_p($subfieldtag);
773 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
775 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);
777 push @fields, "$tag$subfieldtag";
778 push (@loop_data, $subfield_data);
779 $i++;
784 # and now we add fields that are empty
786 # Using last created item if it exists
788 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
790 # We generate form, and fill with values if defined
791 foreach my $tag ( keys %{$tagslib}){
792 foreach my $subtag (keys %{$tagslib->{$tag}}){
793 next if subfield_is_koha_internal_p($subtag);
794 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
795 next if any { /^$tag$subtag$/ } @fields;
797 my @values = (undef);
798 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
799 for my $value (@values){
800 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);
801 push (@loop_data, $subfield_data);
802 $i++;
806 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
808 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
809 $template->param( title => $record->title() ) if ($record ne "-1");
810 $template->param(
811 biblionumber => $biblionumber,
812 title => $oldrecord->{title},
813 author => $oldrecord->{author},
814 item_loop => \@item_value_loop,
815 item_header_loop => \@header_value_loop,
816 item => \@loop_data,
817 itemnumber => $itemnumber,
818 barcode => GetBarcodeFromItemnumber($itemnumber),
819 itemtagfield => $itemtagfield,
820 itemtagsubfield => $itemtagsubfield,
821 op => $nextop,
822 opisadd => ($nextop eq "saveitem") ? 0 : 1,
823 popup => $input->param('popup') ? 1: 0,
824 C4::Search::enabled_staff_search_views,
826 $template->{'VARS'}->{'searchid'} = $searchid;
828 if ($frameworkcode eq 'FA'){
829 # fast cataloguing datas
830 $template->param(
831 'circborrowernumber' => $fa_circborrowernumber,
832 'barcode' => $fa_barcode,
833 'branch' => $fa_branch,
834 'stickyduedate' => $fa_stickyduedate,
835 'duedatespec' => $fa_duedatespec,
839 foreach my $error (@errors) {
840 $template->param($error => 1);
842 output_html_with_http_headers $input, $cookie, $template->output;