Bug 9302: Use patron-title.inc
[koha.git] / cataloguing / additem.pl
blob1b746f7e3074321ef7aaa0d697fcf37e7f6c3121
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use Modern::Perl;
24 use CGI qw ( -utf8 );
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Context;
30 use C4::Circulation;
31 use C4::Koha;
32 use C4::ClassSource;
33 use Koha::DateUtils;
34 use Koha::Items;
35 use Koha::ItemTypes;
36 use Koha::Libraries;
37 use Koha::Patrons;
38 use List::MoreUtils qw/any/;
39 use C4::Search;
40 use Storable qw(thaw freeze);
41 use URI::Escape;
42 use C4::Members;
44 use MARC::File::XML;
45 use URI::Escape;
47 our $dbh = C4::Context->dbh;
49 sub find_value {
50 my ($tagfield,$insubfield,$record) = @_;
51 my $result;
52 my $indicator;
53 foreach my $field ($record->field($tagfield)) {
54 my @subfields = $field->subfields();
55 foreach my $subfield (@subfields) {
56 if (@$subfield[0] eq $insubfield) {
57 $result .= @$subfield[1];
58 $indicator = $field->indicator(1).$field->indicator(2);
62 return($indicator,$result);
65 sub get_item_from_barcode {
66 my ($barcode)=@_;
67 my $dbh=C4::Context->dbh;
68 my $result;
69 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
70 $rq->execute($barcode);
71 ($result)=$rq->fetchrow;
72 return($result);
75 sub set_item_default_location {
76 my $itemnumber = shift;
77 my $item = GetItem( $itemnumber );
78 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
79 $item->{'permanent_location'} = $item->{'location'};
80 $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
81 ModItem( $item, undef, $itemnumber);
83 else {
84 $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
85 ModItem( $item, undef, $itemnumber);
89 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
90 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
91 sub _increment_barcode {
92 my ($record, $frameworkcode) = @_;
93 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
94 unless ($record->field($tagfield)->subfield($tagsubfield)) {
95 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
96 $sth_barcode->execute;
97 my ($newbarcode) = $sth_barcode->fetchrow;
98 $newbarcode++;
99 # OK, we have the new barcode, now create the entry in MARC record
100 my $fieldItem = $record->field($tagfield);
101 $record->delete_field($fieldItem);
102 $fieldItem->add_subfields($tagsubfield => $newbarcode);
103 $record->insert_fields_ordered($fieldItem);
105 return $record;
109 sub generate_subfield_form {
110 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
112 my $frameworkcode = &GetFrameworkCode($biblionumber);
114 my %subfield_data;
115 my $dbh = C4::Context->dbh;
117 my $index_subfield = int(rand(1000000));
118 if ($subfieldtag eq '@'){
119 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
120 } else {
121 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
124 $subfield_data{tag} = $tag;
125 $subfield_data{subfield} = $subfieldtag;
126 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
127 $subfield_data{mandatory} = $subfieldlib->{mandatory};
128 $subfield_data{repeatable} = $subfieldlib->{repeatable};
129 $subfield_data{maxlength} = $subfieldlib->{maxlength};
131 $value =~ s/"/&quot;/g;
132 if ( ! defined( $value ) || $value eq '') {
133 $value = $subfieldlib->{defaultvalue};
134 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
135 my $today_dt = dt_from_string;
136 my $year = $today_dt->strftime('%Y');
137 my $month = $today_dt->strftime('%m');
138 my $day = $today_dt->strftime('%d');
139 $value =~ s/<<YYYY>>/$year/g;
140 $value =~ s/<<MM>>/$month/g;
141 $value =~ s/<<DD>>/$day/g;
142 # And <<USER>> with surname (?)
143 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
144 $value=~s/<<USER>>/$username/g;
147 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
149 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
150 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
151 my $CNtag = substr($pref_itemcallnumber, 0, 3);
152 my $CNsubfield = substr($pref_itemcallnumber, 3, 1);
153 my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
154 my $temp2 = $temp->field($CNtag);
155 if ($temp2) {
156 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
157 #remove any trailing space incase one subfield is used
158 $value =~ s/^\s+|\s+$//g;
162 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
163 my $input = new CGI;
164 $value = $input->param('barcode');
167 if ( $subfieldlib->{authorised_value} ) {
168 my @authorised_values;
169 my %authorised_lib;
170 # builds list, depending on authorised value...
171 if ( $subfieldlib->{authorised_value} eq "branches" ) {
172 foreach my $thisbranch (@$branches) {
173 push @authorised_values, $thisbranch->{branchcode};
174 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
175 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
178 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
179 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
180 my $itemtypes = Koha::ItemTypes->search_with_localization;
181 while ( my $itemtype = $itemtypes->next ) {
182 push @authorised_values, $itemtype->itemtype;
183 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
186 unless ( $value ) {
187 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
188 $itype_sth->execute( $biblionumber );
189 ( $value ) = $itype_sth->fetchrow_array;
192 #---- class_sources
194 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
195 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
197 my $class_sources = GetClassSources();
198 my $default_source = C4::Context->preference("DefaultClassificationSource");
200 foreach my $class_source (sort keys %$class_sources) {
201 next unless $class_sources->{$class_source}->{'used'} or
202 ($value and $class_source eq $value) or
203 ($class_source eq $default_source);
204 push @authorised_values, $class_source;
205 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
207 $value = $default_source unless ($value);
209 #---- "true" authorised value
211 else {
212 push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
213 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
214 for my $r ( @$av ) {
215 push @authorised_values, $r->{authorised_value};
216 $authorised_lib{$r->{authorised_value}} = $r->{lib};
220 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
221 $subfield_data{marc_value} = {
222 type => 'hidden',
223 id => $subfield_data{id},
224 maxlength => $subfield_data{max_length},
225 value => $value,
228 else {
229 $subfield_data{marc_value} = {
230 type => 'select',
231 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
232 values => \@authorised_values,
233 labels => \%authorised_lib,
234 default => $value,
238 # it's a thesaurus / authority field
239 elsif ( $subfieldlib->{authtypecode} ) {
240 $subfield_data{marc_value} = {
241 type => 'text_auth',
242 id => $subfield_data{id},
243 maxlength => $subfield_data{max_length},
244 value => $value,
245 authtypecode => $subfieldlib->{authtypecode},
248 # it's a plugin field
249 elsif ( $subfieldlib->{value_builder} ) { # plugin
250 require Koha::FrameworkPlugin;
251 my $plugin = Koha::FrameworkPlugin->new({
252 name => $subfieldlib->{'value_builder'},
253 item_style => 1,
255 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
256 id => $subfield_data{id}, tabloop => $loop_data };
257 $plugin->build( $pars );
258 if( !$plugin->errstr ) {
259 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
260 $subfield_data{marc_value} = {
261 type => 'text_plugin',
262 id => $subfield_data{id},
263 maxlength => $subfield_data{max_length},
264 value => $value,
265 class => $class,
266 nopopup => $plugin->noclick,
267 javascript => $plugin->javascript,
269 } else {
270 warn $plugin->errstr;
271 $subfield_data{marc_value} = {
272 type => 'text',
273 id => $subfield_data{id},
274 maxlength => $subfield_data{max_length},
275 value => $value,
276 }; # supply default input form
279 elsif ( $tag eq '' ) { # it's an hidden field
280 $subfield_data{marc_value} = {
281 type => 'hidden',
282 id => $subfield_data{id},
283 maxlength => $subfield_data{max_length},
284 value => $value,
287 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
288 $subfield_data{marc_value} = {
289 type => 'text',
290 id => $subfield_data{id},
291 maxlength => $subfield_data{max_length},
292 value => $value,
295 elsif (
296 length($value) > 100
297 or (
298 C4::Context->preference("marcflavour") eq "UNIMARC"
299 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
301 or (
302 C4::Context->preference("marcflavour") eq "MARC21"
303 and 500 <= $tag && $tag < 600
306 # oversize field (textarea)
307 $subfield_data{marc_value} = {
308 type => 'textarea',
309 id => $subfield_data{id},
310 value => $value,
312 } else {
313 # it's a standard field
314 $subfield_data{marc_value} = {
315 type => 'text',
316 id => $subfield_data{id},
317 maxlength => $subfield_data{max_length},
318 value => $value,
322 # Getting list of subfields to keep when restricted editing is enabled
323 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
324 my $allowAllSubfields = (
325 not defined $subfieldsToAllowForRestrictedEditing
326 or $subfieldsToAllowForRestrictedEditing == q||
327 ) ? 1 : 0;
328 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
330 # If we're on restricted editing, and our field is not in the list of subfields to allow,
331 # then it is read-only
332 $subfield_data{marc_value}->{readonly} = (
333 not $allowAllSubfields
334 and $restrictededition
335 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
336 ) ? 1: 0;
338 return \%subfield_data;
341 # Removes some subfields when prefilling items
342 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
343 sub removeFieldsForPrefill {
345 my $item = shift;
347 # Getting item tag
348 my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
350 # Getting list of subfields to keep
351 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
353 # Removing subfields that are not in the syspref
354 if ($tag && $subfieldsToUseWhenPrefill) {
355 my $field = $item->field($tag);
356 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
357 foreach my $subfield ($field->subfields()) {
358 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
359 $field->delete_subfield(code => $subfield->[0]);
365 return $item;
369 my $input = new CGI;
370 my $error = $input->param('error');
371 my $biblionumber = $input->param('biblionumber');
372 my $itemnumber = $input->param('itemnumber');
373 my $op = $input->param('op');
374 my $hostitemnumber = $input->param('hostitemnumber');
375 my $marcflavour = C4::Context->preference("marcflavour");
376 my $searchid = $input->param('searchid');
377 # fast cataloguing datas
378 my $fa_circborrowernumber = $input->param('circborrowernumber');
379 my $fa_barcode = $input->param('barcode');
380 my $fa_branch = $input->param('branch');
381 my $fa_stickyduedate = $input->param('stickyduedate');
382 my $fa_duedatespec = $input->param('duedatespec');
384 my $frameworkcode = &GetFrameworkCode($biblionumber);
386 # Defining which userflag is needing according to the framework currently used
387 my $userflags;
388 if (defined $input->param('frameworkcode')) {
389 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
392 if (not defined $userflags) {
393 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
396 my ($template, $loggedinuser, $cookie)
397 = get_template_and_user({template_name => "cataloguing/additem.tt",
398 query => $input,
399 type => "intranet",
400 authnotrequired => 0,
401 flagsrequired => {editcatalogue => $userflags},
402 debug => 1,
406 # Does the user have a restricted item editing permission?
407 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
408 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
409 # In case user is a superlibrarian, editing is not restricted
410 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
411 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
412 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
414 my $tagslib = &GetMarcStructure(1,$frameworkcode);
415 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
416 my $oldrecord = TransformMarcToKoha($record);
417 my $itemrecord;
418 my $nextop="additem";
419 my @errors; # store errors found while checking data BEFORE saving item.
421 # Getting last created item cookie
422 my $prefillitem = C4::Context->preference('PrefillItem');
423 my $justaddeditem;
424 my $cookieitemrecord;
425 if ($prefillitem) {
426 my $lastitemcookie = $input->cookie('LastCreatedItem');
427 if ($lastitemcookie) {
428 $lastitemcookie = uri_unescape($lastitemcookie);
429 eval {
430 if ( thaw($lastitemcookie) ) {
431 $cookieitemrecord = thaw($lastitemcookie);
432 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
435 if ($@) {
436 $lastitemcookie = 'undef' unless $lastitemcookie;
437 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
442 #-------------------------------------------------------------------------------
443 if ($op eq "additem") {
445 #-------------------------------------------------------------------------------
446 # rebuild
447 my @tags = $input->multi_param('tag');
448 my @subfields = $input->multi_param('subfield');
449 my @values = $input->multi_param('field_value');
450 # build indicator hash.
451 my @ind_tag = $input->multi_param('ind_tag');
452 my @indicator = $input->multi_param('indicator');
453 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
454 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
456 # type of add
457 my $add_submit = $input->param('add_submit');
458 my $add_duplicate_submit = $input->param('add_duplicate_submit');
459 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
460 my $number_of_copies = $input->param('number_of_copies');
462 # This is a bit tricky : if there is a cookie for the last created item and
463 # we just added an item, the cookie value is not correct yet (it will be updated
464 # next page). To prevent the form from being filled with outdated values, we
465 # force the use of "add and duplicate" feature, so the form will be filled with
466 # correct values.
467 $add_duplicate_submit = 1 if ($prefillitem);
468 $justaddeditem = 1;
470 # if autoBarcode is set to 'incremental', calculate barcode...
471 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
472 $record = _increment_barcode($record, $frameworkcode);
475 my $addedolditem = TransformMarcToKoha( $record );
477 # If we have to add or add & duplicate, we add the item
478 if ( $add_submit || $add_duplicate_submit ) {
480 # check for item barcode # being unique
481 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
482 push @errors, "barcode_not_unique" if ($exist_itemnumber);
484 # if barcode exists, don't create, but report The problem.
485 unless ($exist_itemnumber) {
486 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
487 set_item_default_location($oldbibitemnum);
489 # Pushing the last created item cookie back
490 if ($prefillitem && defined $record) {
491 my $itemcookie = $input->cookie(
492 -name => 'LastCreatedItem',
493 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
494 -value => uri_escape_utf8( freeze( $record ) ),
495 -HttpOnly => 1,
496 -expires => ''
499 $cookie = [ $cookie, $itemcookie ];
503 $nextop = "additem";
504 if ($exist_itemnumber) {
505 $itemrecord = $record;
509 # If we have to add & duplicate
510 if ($add_duplicate_submit) {
511 $itemrecord = $record;
512 if (C4::Context->preference('autoBarcode') eq 'incremental') {
513 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
515 else {
516 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
517 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
518 my $fieldItem = $itemrecord->field($tagfield);
519 $itemrecord->delete_field($fieldItem);
520 $fieldItem->delete_subfields($tagsubfield);
521 $itemrecord->insert_fields_ordered($fieldItem);
523 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
526 # If we have to add multiple copies
527 if ($add_multiple_copies_submit) {
529 use C4::Barcodes;
530 my $barcodeobj = C4::Barcodes->new;
531 my $oldbarcode = $addedolditem->{'barcode'};
532 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
534 # If there is a barcode and we can't find their new values, we can't add multiple copies
535 my $testbarcode;
536 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
537 if ($oldbarcode && !$testbarcode) {
539 push @errors, "no_next_barcode";
540 $itemrecord = $record;
542 } else {
543 # We add each item
545 # For the first iteration
546 my $barcodevalue = $oldbarcode;
547 my $exist_itemnumber;
550 for (my $i = 0; $i < $number_of_copies;) {
552 # If there is a barcode
553 if ($barcodevalue) {
555 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
556 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
558 # Putting it into the record
559 if ($barcodevalue) {
560 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
563 # Checking if the barcode already exists
564 $exist_itemnumber = get_item_from_barcode($barcodevalue);
567 # Adding the item
568 if (!$exist_itemnumber) {
569 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
570 set_item_default_location($oldbibitemnum);
572 # We count the item only if it was really added
573 # That way, all items are added, even if there was some already existing barcodes
574 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
575 $i++;
578 # Preparing the next iteration
579 $oldbarcode = $barcodevalue;
581 undef($itemrecord);
584 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
585 print $input->redirect(
586 '/cgi-bin/koha/circ/circulation.pl?'
587 .'borrowernumber='.$fa_circborrowernumber
588 .'&barcode='.uri_escape_utf8($fa_barcode)
589 .'&duedatespec='.$fa_duedatespec
590 .'&stickyduedate=1'
592 exit;
596 #-------------------------------------------------------------------------------
597 } elsif ($op eq "edititem") {
598 #-------------------------------------------------------------------------------
599 # retrieve item if exist => then, it's a modif
600 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
601 $nextop = "saveitem";
602 #-------------------------------------------------------------------------------
603 } elsif ($op eq "dupeitem") {
604 #-------------------------------------------------------------------------------
605 # retrieve item if exist => then, it's a modif
606 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
607 if (C4::Context->preference('autoBarcode') eq 'incremental') {
608 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
610 else {
611 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
612 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
613 my $fieldItem = $itemrecord->field($tagfield);
614 $itemrecord->delete_field($fieldItem);
615 $fieldItem->delete_subfields($tagsubfield);
616 $itemrecord->insert_fields_ordered($fieldItem);
619 #check for hidden subfield and remove them for the duplicated item
620 foreach my $field ($itemrecord->fields()){
621 my $tag = $field->{_tag};
622 foreach my $subfield ($field->subfields()){
623 my $subfieldtag = $subfield->[0];
624 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
625 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
626 my $fieldItem = $itemrecord->field($tag);
627 $itemrecord->delete_field($fieldItem);
628 $fieldItem->delete_subfields($subfieldtag);
629 $itemrecord->insert_fields_ordered($fieldItem);
634 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
635 $nextop = "additem";
636 #-------------------------------------------------------------------------------
637 } elsif ($op eq "delitem") {
638 #-------------------------------------------------------------------------------
639 # check that there is no issue on this item before deletion.
640 $error = &DelItemCheck( $biblionumber,$itemnumber);
641 if($error == 1){
642 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
643 }else{
644 push @errors,$error;
645 $nextop="additem";
647 #-------------------------------------------------------------------------------
648 } elsif ($op eq "delallitems") {
649 #-------------------------------------------------------------------------------
650 my $itemnumbers = C4::Items::GetItemnumbersForBiblio( $biblionumber );
651 foreach my $itemnumber ( @$itemnumbers ) {
652 $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
653 next if $error == 1; # Means ok
654 push @errors,$error;
656 if ( @errors ) {
657 $nextop="additem";
658 } else {
659 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
660 my $views = { C4::Search::enabled_staff_search_views };
661 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
662 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
663 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
664 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
665 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
666 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
667 } else {
668 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
670 exit;
672 #-------------------------------------------------------------------------------
673 } elsif ($op eq "saveitem") {
674 #-------------------------------------------------------------------------------
675 # rebuild
676 my @tags = $input->multi_param('tag');
677 my @subfields = $input->multi_param('subfield');
678 my @values = $input->multi_param('field_value');
679 # build indicator hash.
680 my @ind_tag = $input->multi_param('ind_tag');
681 my @indicator = $input->multi_param('indicator');
682 # my $itemnumber = $input->param('itemnumber');
683 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
684 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
685 # MARC::Record builded => now, record in DB
686 # warn "R: ".$record->as_formatted;
687 # check that the barcode don't exist already
688 my $addedolditem = TransformMarcToKoha($itemtosave);
689 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
690 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
691 push @errors,"barcode_not_unique";
692 } else {
693 my $item = GetItem( $itemnumber );
694 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
695 $itemnumber = q{};
696 my $olditemlost = $item->{itemlost};
697 my $newitemlost = $newitem->{itemlost};
698 LostItem( $item->{itemnumber}, 'additem' )
699 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
701 $nextop="additem";
702 } elsif ($op eq "delinkitem"){
703 my $analyticfield = '773';
704 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
705 $analyticfield = '773';
706 } elsif ($marcflavour eq 'UNIMARC') {
707 $analyticfield = '461';
709 foreach my $field ($record->field($analyticfield)){
710 if ($field->subfield('9') eq $hostitemnumber){
711 $record->delete_field($field);
712 last;
715 my $modbibresult = ModBiblio($record, $biblionumber,'');
719 #-------------------------------------------------------------------------------
720 # build screen with existing items. and "new" one
721 #-------------------------------------------------------------------------------
723 # now, build existiing item list
724 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
725 #my @fields = $record->fields();
728 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
729 my @big_array;
730 #---- finds where items.itemnumber is stored
731 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
732 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
733 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
734 my @fields = $temp->fields();
737 my @hostitemnumbers;
738 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
739 my $analyticfield = '773';
740 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
741 $analyticfield = '773';
742 } elsif ($marcflavour eq 'UNIMARC') {
743 $analyticfield = '461';
745 foreach my $hostfield ($temp->field($analyticfield)){
746 my $hostbiblionumber = $hostfield->subfield('0');
747 if ($hostbiblionumber){
748 my $hostrecord = GetMarcBiblio({
749 biblionumber => $hostbiblionumber,
750 embed_items => 1 });
751 if ($hostrecord) {
752 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
753 foreach my $hostitem ($hostrecord->field($itemfield)){
754 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
755 push (@fields, $hostitem);
756 push (@hostitemnumbers, $hostfield->subfield('9'));
765 foreach my $field (@fields) {
766 next if ( $field->tag() < 10 );
768 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
769 my %this_row;
770 # loop through each subfield
771 my $i = 0;
772 foreach my $subfield (@subf){
773 my $subfieldcode = $subfield->[0];
774 my $subfieldvalue= $subfield->[1];
776 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
777 && ($field->tag() ne $itemtagfield
778 && $subfieldcode ne $itemtagsubfield));
779 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
780 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
781 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
782 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
783 $subfieldcode, $subfieldvalue, '', $tagslib)
784 || $subfieldvalue;
787 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
788 #verifying rights
789 my $userenv = C4::Context->userenv();
790 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
791 $this_row{'nomod'} = 1;
794 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
796 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
797 foreach my $hostitemnumber (@hostitemnumbers){
798 my $item = Koha::Items->find( $hostitemnumber );
799 if ($this_row{itemnumber} eq $hostitemnumber){
800 $this_row{hostitemflag} = 1;
801 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
802 last;
806 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
807 # if ($countanalytics > 0){
808 # $this_row{countanalytics} = $countanalytics;
813 if (%this_row) {
814 push(@big_array, \%this_row);
818 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
819 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
821 # now, construct template !
822 # First, the existing items for display
823 my @item_value_loop;
824 my @header_value_loop;
825 for my $row ( @big_array ) {
826 my %row_data;
827 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
828 $row_data{item_value} = [ @item_fields ];
829 $row_data{itemnumber} = $row->{itemnumber};
830 #reporting this_row values
831 $row_data{'nomod'} = $row->{'nomod'};
832 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
833 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
834 # $row_data{'countanalytics'} = $row->{'countanalytics'};
835 push(@item_value_loop,\%row_data);
837 foreach my $subfield_code (sort keys(%witness)) {
838 my %header_value;
839 $header_value{header_value} = $witness{$subfield_code};
841 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
842 my $kohafield = $subfieldlib->{kohafield};
843 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
844 $header_value{column_name} = $1;
847 push(@header_value_loop, \%header_value);
850 # now, build the item form for entering a new item
851 my @loop_data =();
852 my $i=0;
854 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
856 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
857 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
858 for my $library ( @$libraries ) {
859 $library->{selected} = 1 if $library->{branchcode} eq $branch
862 # We generate form, from actuel record
863 @fields = ();
864 if($itemrecord){
865 foreach my $field ($itemrecord->fields()){
866 my $tag = $field->{_tag};
867 foreach my $subfield ( $field->subfields() ){
869 my $subfieldtag = $subfield->[0];
870 my $value = $subfield->[1];
871 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
873 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
875 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
876 push @fields, "$tag$subfieldtag";
877 push (@loop_data, $subfield_data);
878 $i++;
883 # and now we add fields that are empty
885 # Using last created item if it exists
887 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
889 # We generate form, and fill with values if defined
890 foreach my $tag ( keys %{$tagslib}){
891 foreach my $subtag (keys %{$tagslib->{$tag}}){
892 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
893 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
894 next if any { /^$tag$subtag$/ } @fields;
896 my @values = (undef);
897 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
898 for my $value (@values){
899 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
900 push (@loop_data, $subfield_data);
901 $i++;
905 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
907 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
908 $template->param(
909 biblionumber => $biblionumber,
910 title => $oldrecord->{title},
911 author => $oldrecord->{author},
912 item_loop => \@item_value_loop,
913 item_header_loop => \@header_value_loop,
914 item => \@loop_data,
915 itemnumber => $itemnumber,
916 barcode => GetBarcodeFromItemnumber($itemnumber),
917 itemtagfield => $itemtagfield,
918 itemtagsubfield => $itemtagsubfield,
919 op => $nextop,
920 opisadd => ($nextop eq "saveitem") ? 0 : 1,
921 popup => scalar $input->param('popup') ? 1: 0,
922 C4::Search::enabled_staff_search_views,
924 $template->{'VARS'}->{'searchid'} = $searchid;
926 if ($frameworkcode eq 'FA'){
927 # fast cataloguing datas
928 $template->param(
929 'circborrowernumber' => $fa_circborrowernumber,
930 'barcode' => $fa_barcode,
931 'branch' => $fa_branch,
932 'stickyduedate' => $fa_stickyduedate,
933 'duedatespec' => $fa_duedatespec,
937 foreach my $error (@errors) {
938 $template->param($error => 1);
940 output_html_with_http_headers $input, $cookie, $template->output;