Bug 17670: Grammar mistakes - effect vs affect
[koha.git] / cataloguing / additem.pl
blob9f0f146b48a719b6c85c649e9b1cc4e148b7af70
1 #!/usr/bin/perl
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use CGI qw ( -utf8 );
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Context;
30 use C4::Circulation;
31 use C4::Koha;
32 use C4::ClassSource;
33 use Koha::DateUtils;
34 use Koha::Libraries;
35 use List::MoreUtils qw/any/;
36 use C4::Search;
37 use Storable qw(thaw freeze);
38 use URI::Escape;
39 use C4::Members;
41 use MARC::File::XML;
42 use URI::Escape;
44 our $dbh = C4::Context->dbh;
46 sub find_value {
47 my ($tagfield,$insubfield,$record) = @_;
48 my $result;
49 my $indicator;
50 foreach my $field ($record->field($tagfield)) {
51 my @subfields = $field->subfields();
52 foreach my $subfield (@subfields) {
53 if (@$subfield[0] eq $insubfield) {
54 $result .= @$subfield[1];
55 $indicator = $field->indicator(1).$field->indicator(2);
59 return($indicator,$result);
62 sub get_item_from_barcode {
63 my ($barcode)=@_;
64 my $dbh=C4::Context->dbh;
65 my $result;
66 my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
67 $rq->execute($barcode);
68 ($result)=$rq->fetchrow;
69 return($result);
72 sub set_item_default_location {
73 my $itemnumber = shift;
74 my $item = GetItem( $itemnumber );
75 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
76 $item->{'permanent_location'} = $item->{'location'};
77 $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
78 ModItem( $item, undef, $itemnumber);
80 else {
81 $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
82 ModItem( $item, undef, $itemnumber);
86 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
87 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
88 sub _increment_barcode {
89 my ($record, $frameworkcode) = @_;
90 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
91 unless ($record->field($tagfield)->subfield($tagsubfield)) {
92 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
93 $sth_barcode->execute;
94 my ($newbarcode) = $sth_barcode->fetchrow;
95 $newbarcode++;
96 # OK, we have the new barcode, now create the entry in MARC record
97 my $fieldItem = $record->field($tagfield);
98 $record->delete_field($fieldItem);
99 $fieldItem->add_subfields($tagsubfield => $newbarcode);
100 $record->insert_fields_ordered($fieldItem);
102 return $record;
106 sub generate_subfield_form {
107 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
109 my $frameworkcode = &GetFrameworkCode($biblionumber);
111 my %subfield_data;
112 my $dbh = C4::Context->dbh;
114 my $index_subfield = int(rand(1000000));
115 if ($subfieldtag eq '@'){
116 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
117 } else {
118 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
121 $subfield_data{tag} = $tag;
122 $subfield_data{subfield} = $subfieldtag;
123 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
124 $subfield_data{mandatory} = $subfieldlib->{mandatory};
125 $subfield_data{repeatable} = $subfieldlib->{repeatable};
126 $subfield_data{maxlength} = $subfieldlib->{maxlength};
128 $value =~ s/"/&quot;/g;
129 if ( ! defined( $value ) || $value eq '') {
130 $value = $subfieldlib->{defaultvalue};
131 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
132 my $today_dt = dt_from_string;
133 my $year = $today_dt->year;
134 my $month = $today_dt->month;
135 my $day = $today_dt->day;
136 $value =~ s/<<YYYY>>/$year/g;
137 $value =~ s/<<MM></$month/g;
138 $value =~ s/<<DD>>/$day/g;
139 # And <<USER>> with surname (?)
140 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
141 $value=~s/<<USER>>/$username/g;
144 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
146 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
147 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
148 my $CNtag = substr($pref_itemcallnumber, 0, 3);
149 my $CNsubfield = substr($pref_itemcallnumber, 3, 1);
150 my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
151 my $temp2 = $temp->field($CNtag);
152 if ($temp2) {
153 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
154 #remove any trailing space incase one subfield is used
155 $value =~ s/^\s+|\s+$//g;
159 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
160 my $input = new CGI;
161 $value = $input->param('barcode');
164 # Getting list of subfields to keep when restricted editing is enabled
165 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
166 my $allowAllSubfields = (
167 not defined $subfieldsToAllowForRestrictedEditing
168 or $subfieldsToAllowForRestrictedEditing == q||
169 ) ? 1 : 0;
170 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
172 if ( $subfieldlib->{authorised_value} ) {
173 my @authorised_values;
174 my %authorised_lib;
175 # builds list, depending on authorised value...
176 if ( $subfieldlib->{authorised_value} eq "branches" ) {
177 foreach my $thisbranch (@$branches) {
178 push @authorised_values, $thisbranch->{branchcode};
179 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
180 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
183 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
184 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
185 my $itemtypes = GetItemTypes( style => 'array' );
186 for my $itemtype ( @$itemtypes ) {
187 push @authorised_values, $itemtype->{itemtype};
188 $authorised_lib{$itemtype->{itemtype}} = $itemtype->{translated_description};
191 unless ( $value ) {
192 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
193 $itype_sth->execute( $biblionumber );
194 ( $value ) = $itype_sth->fetchrow_array;
197 #---- class_sources
199 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
200 push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
202 my $class_sources = GetClassSources();
203 my $default_source = C4::Context->preference("DefaultClassificationSource");
205 foreach my $class_source (sort keys %$class_sources) {
206 next unless $class_sources->{$class_source}->{'used'} or
207 ($value and $class_source eq $value) or
208 ($class_source eq $default_source);
209 push @authorised_values, $class_source;
210 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
212 $value = $default_source unless ($value);
214 #---- "true" authorised value
216 else {
217 push @authorised_values, qq{} unless ( $subfieldlib->{mandatory} );
218 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
219 for my $r ( @$av ) {
220 push @authorised_values, $r->{authorised_value};
221 $authorised_lib{$r->{authorised_value}} = $r->{lib};
225 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
226 $subfield_data{marc_value} = {
227 type => 'hidden',
228 id => $subfield_data{id},
229 maxlength => $subfield_data{max_length},
230 value => $value,
233 else {
234 $subfield_data{marc_value} = {
235 type => 'select',
236 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
237 values => \@authorised_values,
238 labels => \%authorised_lib,
239 default => $value,
241 # If we're on restricted editing, and our field is not in the list of subfields to allow,
242 # then it is read-only
243 $subfield_data{marc_value}->{readonlyselect} = (
244 not $allowAllSubfields
245 and $restrictededition
246 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
247 ) ? 1: 0;
250 # it's a thesaurus / authority field
251 elsif ( $subfieldlib->{authtypecode} ) {
252 $subfield_data{marc_value} = {
253 type => 'text_auth',
254 id => $subfield_data{id},
255 maxlength => $subfield_data{max_length},
256 value => $value,
257 authtypecode => $subfieldlib->{authtypecode},
260 # it's a plugin field
261 elsif ( $subfieldlib->{value_builder} ) { # plugin
262 require Koha::FrameworkPlugin;
263 my $plugin = Koha::FrameworkPlugin->new({
264 name => $subfieldlib->{'value_builder'},
265 item_style => 1,
267 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
268 id => $subfield_data{id}, tabloop => $loop_data };
269 $plugin->build( $pars );
270 if( !$plugin->errstr ) {
271 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
272 $subfield_data{marc_value} = {
273 type => 'text_plugin',
274 id => $subfield_data{id},
275 maxlength => $subfield_data{max_length},
276 value => $value,
277 class => $class,
278 nopopup => $plugin->noclick,
279 javascript => $plugin->javascript,
281 } else {
282 warn $plugin->errstr;
283 $subfield_data{marc_value} = {
284 type => 'text',
285 id => $subfield_data{id},
286 maxlength => $subfield_data{max_length},
287 value => $value,
288 }; # supply default input form
291 elsif ( $tag eq '' ) { # it's an hidden field
292 $subfield_data{marc_value} = {
293 type => 'hidden',
294 id => $subfield_data{id},
295 maxlength => $subfield_data{max_length},
296 value => $value,
299 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
300 $subfield_data{marc_value} = {
301 type => 'text',
302 id => $subfield_data{id},
303 maxlength => $subfield_data{max_length},
304 value => $value,
307 elsif (
308 length($value) > 100
309 or (
310 C4::Context->preference("marcflavour") eq "UNIMARC"
311 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
313 or (
314 C4::Context->preference("marcflavour") eq "MARC21"
315 and 500 <= $tag && $tag < 600
318 # oversize field (textarea)
319 $subfield_data{marc_value} = {
320 type => 'textarea',
321 id => $subfield_data{id},
322 value => $value,
324 } else {
325 # it's a standard field
326 $subfield_data{marc_value} = {
327 type => 'text',
328 id => $subfield_data{id},
329 maxlength => $subfield_data{max_length},
330 value => $value,
334 return \%subfield_data;
337 # Removes some subfields when prefilling items
338 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
339 sub removeFieldsForPrefill {
341 my $item = shift;
343 # Getting item tag
344 my ($tag, $subtag) = GetMarcFromKohaField("items.barcode", '');
346 # Getting list of subfields to keep
347 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
349 # Removing subfields that are not in the syspref
350 if ($tag && $subfieldsToUseWhenPrefill) {
351 my $field = $item->field($tag);
352 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
353 foreach my $subfield ($field->subfields()) {
354 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
355 $field->delete_subfield(code => $subfield->[0]);
361 return $item;
365 my $input = new CGI;
366 my $error = $input->param('error');
367 my $biblionumber = $input->param('biblionumber');
368 my $itemnumber = $input->param('itemnumber');
369 my $op = $input->param('op');
370 my $hostitemnumber = $input->param('hostitemnumber');
371 my $marcflavour = C4::Context->preference("marcflavour");
372 my $searchid = $input->param('searchid');
373 # fast cataloguing datas
374 my $fa_circborrowernumber = $input->param('circborrowernumber');
375 my $fa_barcode = $input->param('barcode');
376 my $fa_branch = $input->param('branch');
377 my $fa_stickyduedate = $input->param('stickyduedate');
378 my $fa_duedatespec = $input->param('duedatespec');
380 my $frameworkcode = &GetFrameworkCode($biblionumber);
382 # Defining which userflag is needing according to the framework currently used
383 my $userflags;
384 if (defined $input->param('frameworkcode')) {
385 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
388 if (not defined $userflags) {
389 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
392 my ($template, $loggedinuser, $cookie)
393 = get_template_and_user({template_name => "cataloguing/additem.tt",
394 query => $input,
395 type => "intranet",
396 authnotrequired => 0,
397 flagsrequired => {editcatalogue => $userflags},
398 debug => 1,
402 # Does the user have a restricted item editing permission?
403 my $uid = $loggedinuser ? GetMember( borrowernumber => $loggedinuser )->{userid} : undef;
404 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
405 # In case user is a superlibrarian, editing is not restricted
406 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
407 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
408 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
410 my $tagslib = &GetMarcStructure(1,$frameworkcode);
411 my $record = GetMarcBiblio($biblionumber);
412 my $oldrecord = TransformMarcToKoha($record);
413 my $itemrecord;
414 my $nextop="additem";
415 my @errors; # store errors found while checking data BEFORE saving item.
417 # Getting last created item cookie
418 my $prefillitem = C4::Context->preference('PrefillItem');
419 my $justaddeditem;
420 my $cookieitemrecord;
421 if ($prefillitem) {
422 my $lastitemcookie = $input->cookie('LastCreatedItem');
423 if ($lastitemcookie) {
424 $lastitemcookie = uri_unescape($lastitemcookie);
425 eval {
426 if ( thaw($lastitemcookie) ) {
427 $cookieitemrecord = thaw($lastitemcookie);
428 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
431 if ($@) {
432 $lastitemcookie = 'undef' unless $lastitemcookie;
433 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
438 #-------------------------------------------------------------------------------
439 if ($op eq "additem") {
441 #-------------------------------------------------------------------------------
442 # rebuild
443 my @tags = $input->multi_param('tag');
444 my @subfields = $input->multi_param('subfield');
445 my @values = $input->multi_param('field_value');
446 # build indicator hash.
447 my @ind_tag = $input->multi_param('ind_tag');
448 my @indicator = $input->multi_param('indicator');
449 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
450 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
452 # type of add
453 my $add_submit = $input->param('add_submit');
454 my $add_duplicate_submit = $input->param('add_duplicate_submit');
455 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
456 my $number_of_copies = $input->param('number_of_copies');
458 # This is a bit tricky : if there is a cookie for the last created item and
459 # we just added an item, the cookie value is not correct yet (it will be updated
460 # next page). To prevent the form from being filled with outdated values, we
461 # force the use of "add and duplicate" feature, so the form will be filled with
462 # correct values.
463 $add_duplicate_submit = 1 if ($prefillitem);
464 $justaddeditem = 1;
466 # if autoBarcode is set to 'incremental', calculate barcode...
467 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
468 $record = _increment_barcode($record, $frameworkcode);
471 my $addedolditem = TransformMarcToKoha( $record );
473 # If we have to add or add & duplicate, we add the item
474 if ( $add_submit || $add_duplicate_submit ) {
476 # check for item barcode # being unique
477 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
478 push @errors, "barcode_not_unique" if ($exist_itemnumber);
480 # if barcode exists, don't create, but report The problem.
481 unless ($exist_itemnumber) {
482 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
483 set_item_default_location($oldbibitemnum);
485 # Pushing the last created item cookie back
486 if ($prefillitem && defined $record) {
487 my $itemcookie = $input->cookie(
488 -name => 'LastCreatedItem',
489 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
490 -value => uri_escape_utf8( freeze( $record ) ),
491 -HttpOnly => 1,
492 -expires => ''
495 $cookie = [ $cookie, $itemcookie ];
499 $nextop = "additem";
500 if ($exist_itemnumber) {
501 $itemrecord = $record;
505 # If we have to add & duplicate
506 if ($add_duplicate_submit) {
507 $itemrecord = $record;
508 if (C4::Context->preference('autoBarcode') eq 'incremental') {
509 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
511 else {
512 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
513 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
514 my $fieldItem = $itemrecord->field($tagfield);
515 $itemrecord->delete_field($fieldItem);
516 $fieldItem->delete_subfields($tagsubfield);
517 $itemrecord->insert_fields_ordered($fieldItem);
519 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
522 # If we have to add multiple copies
523 if ($add_multiple_copies_submit) {
525 use C4::Barcodes;
526 my $barcodeobj = C4::Barcodes->new;
527 my $oldbarcode = $addedolditem->{'barcode'};
528 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
530 # If there is a barcode and we can't find him new values, we can't add multiple copies
531 my $testbarcode;
532 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
533 if ($oldbarcode && !$testbarcode) {
535 push @errors, "no_next_barcode";
536 $itemrecord = $record;
538 } else {
539 # We add each item
541 # For the first iteration
542 my $barcodevalue = $oldbarcode;
543 my $exist_itemnumber;
546 for (my $i = 0; $i < $number_of_copies;) {
548 # If there is a barcode
549 if ($barcodevalue) {
551 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
552 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
554 # Putting it into the record
555 if ($barcodevalue) {
556 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
559 # Checking if the barcode already exists
560 $exist_itemnumber = get_item_from_barcode($barcodevalue);
563 # Adding the item
564 if (!$exist_itemnumber) {
565 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
566 set_item_default_location($oldbibitemnum);
568 # We count the item only if it was really added
569 # That way, all items are added, even if there was some already existing barcodes
570 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
571 $i++;
574 # Preparing the next iteration
575 $oldbarcode = $barcodevalue;
577 undef($itemrecord);
580 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
581 print $input->redirect(
582 '/cgi-bin/koha/circ/circulation.pl?'
583 .'borrowernumber='.$fa_circborrowernumber
584 .'&barcode='.uri_escape_utf8($fa_barcode)
585 .'&duedatespec='.$fa_duedatespec
586 .'&stickyduedate=1'
588 exit;
592 #-------------------------------------------------------------------------------
593 } elsif ($op eq "edititem") {
594 #-------------------------------------------------------------------------------
595 # retrieve item if exist => then, it's a modif
596 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
597 $nextop = "saveitem";
598 #-------------------------------------------------------------------------------
599 } elsif ($op eq "dupeitem") {
600 #-------------------------------------------------------------------------------
601 # retrieve item if exist => then, it's a modif
602 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
603 if (C4::Context->preference('autoBarcode') eq 'incremental') {
604 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
606 else {
607 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
608 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
609 my $fieldItem = $itemrecord->field($tagfield);
610 $itemrecord->delete_field($fieldItem);
611 $fieldItem->delete_subfields($tagsubfield);
612 $itemrecord->insert_fields_ordered($fieldItem);
615 #check for hidden subfield and remove them for the duplicated item
616 foreach my $field ($itemrecord->fields()){
617 my $tag = $field->{_tag};
618 foreach my $subfield ($field->subfields()){
619 my $subfieldtag = $subfield->[0];
620 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
621 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
622 my $fieldItem = $itemrecord->field($tag);
623 $itemrecord->delete_field($fieldItem);
624 $fieldItem->delete_subfields($subfieldtag);
625 $itemrecord->insert_fields_ordered($fieldItem);
630 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
631 $nextop = "additem";
632 #-------------------------------------------------------------------------------
633 } elsif ($op eq "delitem") {
634 #-------------------------------------------------------------------------------
635 # check that there is no issue on this item before deletion.
636 $error = &DelItemCheck( $biblionumber,$itemnumber);
637 if($error == 1){
638 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
639 }else{
640 push @errors,$error;
641 $nextop="additem";
643 #-------------------------------------------------------------------------------
644 } elsif ($op eq "delallitems") {
645 #-------------------------------------------------------------------------------
646 my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
647 my $errortest=0;
648 my $itemfail;
649 foreach my $biblioitem (@biblioitems) {
650 my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
652 foreach my $item (@$items) {
653 $error =&DelItemCheck( $biblionumber, $item->{itemnumber} );
654 $itemfail =$item;
655 if($error == 1){
656 next
658 else {
659 push @errors,$error;
660 $errortest++
663 if($errortest > 0){
664 $nextop="additem";
666 else {
667 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
668 my $views = { C4::Search::enabled_staff_search_views };
669 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
670 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
671 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
672 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
673 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
674 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
675 } else {
676 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
678 exit;
681 #-------------------------------------------------------------------------------
682 } elsif ($op eq "saveitem") {
683 #-------------------------------------------------------------------------------
684 # rebuild
685 my @tags = $input->multi_param('tag');
686 my @subfields = $input->multi_param('subfield');
687 my @values = $input->multi_param('field_value');
688 # build indicator hash.
689 my @ind_tag = $input->multi_param('ind_tag');
690 my @indicator = $input->multi_param('indicator');
691 # my $itemnumber = $input->param('itemnumber');
692 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
693 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
694 # MARC::Record builded => now, record in DB
695 # warn "R: ".$record->as_formatted;
696 # check that the barcode don't exist already
697 my $addedolditem = TransformMarcToKoha($itemtosave);
698 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
699 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
700 push @errors,"barcode_not_unique";
701 } else {
702 ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
703 $itemnumber="";
705 my $item = GetItem( $itemnumber );
706 my $olditemlost = $item->{'itemlost'};
708 my ($lost_tag,$lost_subfield) = GetMarcFromKohaField("items.itemlost",'');
710 my $newitemlost = $itemtosave->subfield( $lost_tag, $lost_subfield );
711 if (($olditemlost eq '0' or $olditemlost eq '' ) and $newitemlost ge '1'){
712 LostItem($itemnumber,'MARK RETURNED');
714 $nextop="additem";
715 } elsif ($op eq "delinkitem"){
716 my $analyticfield = '773';
717 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
718 $analyticfield = '773';
719 } elsif ($marcflavour eq 'UNIMARC') {
720 $analyticfield = '461';
722 foreach my $field ($record->field($analyticfield)){
723 if ($field->subfield('9') eq $hostitemnumber){
724 $record->delete_field($field);
725 last;
728 my $modbibresult = ModBiblio($record, $biblionumber,'');
732 #-------------------------------------------------------------------------------
733 # build screen with existing items. and "new" one
734 #-------------------------------------------------------------------------------
736 # now, build existiing item list
737 my $temp = GetMarcBiblio( $biblionumber );
738 #my @fields = $record->fields();
741 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
742 my @big_array;
743 #---- finds where items.itemnumber is stored
744 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
745 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
746 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
747 my @fields = $temp->fields();
750 my @hostitemnumbers;
751 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
752 my $analyticfield = '773';
753 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
754 $analyticfield = '773';
755 } elsif ($marcflavour eq 'UNIMARC') {
756 $analyticfield = '461';
758 foreach my $hostfield ($temp->field($analyticfield)){
759 my $hostbiblionumber = $hostfield->subfield('0');
760 if ($hostbiblionumber){
761 my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
762 if ($hostrecord) {
763 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
764 foreach my $hostitem ($hostrecord->field($itemfield)){
765 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
766 push (@fields, $hostitem);
767 push (@hostitemnumbers, $hostfield->subfield('9'));
776 foreach my $field (@fields) {
777 next if ( $field->tag() < 10 );
779 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
780 my %this_row;
781 # loop through each subfield
782 my $i = 0;
783 foreach my $subfield (@subf){
784 my $subfieldcode = $subfield->[0];
785 my $subfieldvalue= $subfield->[1];
787 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
788 && ($field->tag() ne $itemtagfield
789 && $subfieldcode ne $itemtagsubfield));
790 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
791 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
792 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
793 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
794 $subfieldcode, $subfieldvalue, '', $tagslib)
795 || $subfieldvalue;
798 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
799 #verifying rights
800 my $userenv = C4::Context->userenv();
801 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
802 $this_row{'nomod'} = 1;
805 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
807 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
808 foreach my $hostitemnumber (@hostitemnumbers){
809 if ($this_row{itemnumber} eq $hostitemnumber){
810 $this_row{hostitemflag} = 1;
811 $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
812 last;
816 # my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
817 # if ($countanalytics > 0){
818 # $this_row{countanalytics} = $countanalytics;
823 if (%this_row) {
824 push(@big_array, \%this_row);
828 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
829 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
831 # now, construct template !
832 # First, the existing items for display
833 my @item_value_loop;
834 my @header_value_loop;
835 for my $row ( @big_array ) {
836 my %row_data;
837 my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
838 $row_data{item_value} = [ @item_fields ];
839 $row_data{itemnumber} = $row->{itemnumber};
840 #reporting this_row values
841 $row_data{'nomod'} = $row->{'nomod'};
842 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
843 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
844 # $row_data{'countanalytics'} = $row->{'countanalytics'};
845 push(@item_value_loop,\%row_data);
847 foreach my $subfield_code (sort keys(%witness)) {
848 my %header_value;
849 $header_value{header_value} = $witness{$subfield_code};
851 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
852 my $kohafield = $subfieldlib->{kohafield};
853 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
854 $header_value{column_name} = $1;
857 push(@header_value_loop, \%header_value);
860 # now, build the item form for entering a new item
861 my @loop_data =();
862 my $i=0;
864 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
866 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
867 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
868 for my $library ( @$libraries ) {
869 $library->{selected} = 1 if $library->{branchcode} eq $branch
872 # We generate form, from actuel record
873 @fields = ();
874 if($itemrecord){
875 foreach my $field ($itemrecord->fields()){
876 my $tag = $field->{_tag};
877 foreach my $subfield ( $field->subfields() ){
879 my $subfieldtag = $subfield->[0];
880 my $value = $subfield->[1];
881 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
883 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
885 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
886 push @fields, "$tag$subfieldtag";
887 push (@loop_data, $subfield_data);
888 $i++;
893 # and now we add fields that are empty
895 # Using last created item if it exists
897 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
899 # We generate form, and fill with values if defined
900 foreach my $tag ( keys %{$tagslib}){
901 foreach my $subtag (keys %{$tagslib->{$tag}}){
902 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
903 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
904 next if any { /^$tag$subtag$/ } @fields;
906 my @values = (undef);
907 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
908 for my $value (@values){
909 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
910 push (@loop_data, $subfield_data);
911 $i++;
915 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
917 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
918 $template->param(
919 biblionumber => $biblionumber,
920 title => $oldrecord->{title},
921 author => $oldrecord->{author},
922 item_loop => \@item_value_loop,
923 item_header_loop => \@header_value_loop,
924 item => \@loop_data,
925 itemnumber => $itemnumber,
926 barcode => GetBarcodeFromItemnumber($itemnumber),
927 itemtagfield => $itemtagfield,
928 itemtagsubfield => $itemtagsubfield,
929 op => $nextop,
930 opisadd => ($nextop eq "saveitem") ? 0 : 1,
931 popup => scalar $input->param('popup') ? 1: 0,
932 C4::Search::enabled_staff_search_views,
934 $template->{'VARS'}->{'searchid'} = $searchid;
936 if ($frameworkcode eq 'FA'){
937 # fast cataloguing datas
938 $template->param(
939 'circborrowernumber' => $fa_circborrowernumber,
940 'barcode' => $fa_barcode,
941 'branch' => $fa_branch,
942 'stickyduedate' => $fa_stickyduedate,
943 'duedatespec' => $fa_duedatespec,
947 foreach my $error (@errors) {
948 $template->param($error => 1);
950 output_html_with_http_headers $input, $cookie, $template->output;