Bug 21443: Update Schema
[koha.git] / cataloguing / additem.pl
blobec27c1a4260b24c3223a6fffd412398e14404b14
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 = Koha::Items->find($itemnumber);
78 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
79 $item->permanent_location($item->location);
80 $item->location(C4::Context->preference('NewItemsDefaultLocation'));
82 else {
83 # It seems that we are dealing with that in too many places
84 $item->permanent_location($item->location) unless defined $item->permanent_location;
86 $item->store;
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" );
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{important} = $subfieldlib->{important};
129 $subfield_data{repeatable} = $subfieldlib->{repeatable};
130 $subfield_data{maxlength} = $subfieldlib->{maxlength};
132 if ( ! defined( $value ) || $value eq '') {
133 $value = $subfieldlib->{defaultvalue};
134 if ( $value ) {
135 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
136 my $today_dt = dt_from_string;
137 my $year = $today_dt->strftime('%Y');
138 my $month = $today_dt->strftime('%m');
139 my $day = $today_dt->strftime('%d');
140 $value =~ s/<<YYYY>>/$year/g;
141 $value =~ s/<<MM>>/$month/g;
142 $value =~ s/<<DD>>/$day/g;
143 # And <<USER>> with surname (?)
144 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
145 $value=~s/<<USER>>/$username/g;
149 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
151 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
152 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
153 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
154 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
155 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
156 my $temp2 = $temp->field($CNtag);
158 next unless $temp2;
159 $value = $temp2->as_string( $CNsubfields, ' ' );
160 last if $value;
164 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
165 my $input = new CGI;
166 $value = $input->param('barcode');
169 if ( $subfieldlib->{authorised_value} ) {
170 my @authorised_values;
171 my %authorised_lib;
172 # builds list, depending on authorised value...
173 if ( $subfieldlib->{authorised_value} eq "branches" ) {
174 foreach my $thisbranch (@$branches) {
175 push @authorised_values, $thisbranch->{branchcode};
176 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
177 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
180 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
181 push @authorised_values, "";
182 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
183 my $itemtypes;
184 if($branch_limit) {
185 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
186 } else {
187 $itemtypes = Koha::ItemTypes->search_with_localization;
189 while ( my $itemtype = $itemtypes->next ) {
190 push @authorised_values, $itemtype->itemtype;
191 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
194 unless ( $value ) {
195 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
196 $itype_sth->execute( $biblionumber );
197 ( $value ) = $itype_sth->fetchrow_array;
200 #---- class_sources
202 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
203 push @authorised_values, "";
205 my $class_sources = GetClassSources();
206 my $default_source = C4::Context->preference("DefaultClassificationSource");
208 foreach my $class_source (sort keys %$class_sources) {
209 next unless $class_sources->{$class_source}->{'used'} or
210 ($value and $class_source eq $value) or
211 ($class_source eq $default_source);
212 push @authorised_values, $class_source;
213 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
215 $value = $default_source unless ($value);
217 #---- "true" authorised value
219 else {
220 push @authorised_values, qq{};
221 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
222 for my $r ( @$av ) {
223 push @authorised_values, $r->{authorised_value};
224 $authorised_lib{$r->{authorised_value}} = $r->{lib};
228 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
229 $subfield_data{marc_value} = {
230 type => 'hidden',
231 id => $subfield_data{id},
232 maxlength => $subfield_data{maxlength},
233 value => $value,
236 else {
237 $subfield_data{marc_value} = {
238 type => 'select',
239 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
240 values => \@authorised_values,
241 labels => \%authorised_lib,
242 default => $value,
246 # it's a thesaurus / authority field
247 elsif ( $subfieldlib->{authtypecode} ) {
248 $subfield_data{marc_value} = {
249 type => 'text_auth',
250 id => $subfield_data{id},
251 maxlength => $subfield_data{maxlength},
252 value => $value,
253 authtypecode => $subfieldlib->{authtypecode},
256 # it's a plugin field
257 elsif ( $subfieldlib->{value_builder} ) { # plugin
258 require Koha::FrameworkPlugin;
259 my $plugin = Koha::FrameworkPlugin->new({
260 name => $subfieldlib->{'value_builder'},
261 item_style => 1,
263 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
264 id => $subfield_data{id}, tabloop => $loop_data };
265 $plugin->build( $pars );
266 if( !$plugin->errstr ) {
267 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
268 $subfield_data{marc_value} = {
269 type => 'text_plugin',
270 id => $subfield_data{id},
271 maxlength => $subfield_data{maxlength},
272 value => $value,
273 class => $class,
274 nopopup => $plugin->noclick,
275 javascript => $plugin->javascript,
277 } else {
278 warn $plugin->errstr;
279 $subfield_data{marc_value} = {
280 type => 'text',
281 id => $subfield_data{id},
282 maxlength => $subfield_data{maxlength},
283 value => $value,
284 }; # supply default input form
287 elsif ( $tag eq '' ) { # it's an hidden field
288 $subfield_data{marc_value} = {
289 type => 'hidden',
290 id => $subfield_data{id},
291 maxlength => $subfield_data{maxlength},
292 value => $value,
295 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
296 $subfield_data{marc_value} = {
297 type => 'text',
298 id => $subfield_data{id},
299 maxlength => $subfield_data{maxlength},
300 value => $value,
303 elsif (
305 $value and length($value) > 100
307 or (
308 C4::Context->preference("marcflavour") eq "UNIMARC"
309 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
311 or (
312 C4::Context->preference("marcflavour") eq "MARC21"
313 and 500 <= $tag && $tag < 600
316 # oversize field (textarea)
317 $subfield_data{marc_value} = {
318 type => 'textarea',
319 id => $subfield_data{id},
320 value => $value,
322 } else {
323 # it's a standard field
324 $subfield_data{marc_value} = {
325 type => 'text',
326 id => $subfield_data{id},
327 maxlength => $subfield_data{maxlength},
328 value => $value,
332 # Getting list of subfields to keep when restricted editing is enabled
333 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
334 my $allowAllSubfields = (
335 not defined $subfieldsToAllowForRestrictedEditing
336 or $subfieldsToAllowForRestrictedEditing eq q||
337 ) ? 1 : 0;
338 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
340 # If we're on restricted editing, and our field is not in the list of subfields to allow,
341 # then it is read-only
342 $subfield_data{marc_value}->{readonly} = (
343 not $allowAllSubfields
344 and $restrictededition
345 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
346 ) ? 1: 0;
348 return \%subfield_data;
351 # Removes some subfields when prefilling items
352 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
353 sub removeFieldsForPrefill {
355 my $item = shift;
357 # Getting item tag
358 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
360 # Getting list of subfields to keep
361 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
363 # Removing subfields that are not in the syspref
364 if ($tag && $subfieldsToUseWhenPrefill) {
365 my $field = $item->field($tag);
366 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
367 foreach my $subfield ($field->subfields()) {
368 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
369 $field->delete_subfield(code => $subfield->[0]);
375 return $item;
379 my $input = new CGI;
380 my $error = $input->param('error');
381 my $biblionumber = $input->param('biblionumber');
382 my $itemnumber = $input->param('itemnumber');
383 my $op = $input->param('op') || q{};
384 my $hostitemnumber = $input->param('hostitemnumber');
385 my $marcflavour = C4::Context->preference("marcflavour");
386 my $searchid = $input->param('searchid');
387 # fast cataloguing datas
388 my $fa_circborrowernumber = $input->param('circborrowernumber');
389 my $fa_barcode = $input->param('barcode');
390 my $fa_branch = $input->param('branch');
391 my $fa_stickyduedate = $input->param('stickyduedate');
392 my $fa_duedatespec = $input->param('duedatespec');
394 my $frameworkcode = &GetFrameworkCode($biblionumber);
396 # Defining which userflag is needing according to the framework currently used
397 my $userflags;
398 if (defined $input->param('frameworkcode')) {
399 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
402 if (not defined $userflags) {
403 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
406 my ($template, $loggedinuser, $cookie)
407 = get_template_and_user({template_name => "cataloguing/additem.tt",
408 query => $input,
409 type => "intranet",
410 authnotrequired => 0,
411 flagsrequired => {editcatalogue => $userflags},
412 debug => 1,
416 # Does the user have a restricted item editing permission?
417 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
418 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
419 # In case user is a superlibrarian, editing is not restricted
420 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
421 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
422 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
424 my $tagslib = &GetMarcStructure(1,$frameworkcode);
425 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
427 output_and_exit_if_error( $input, $cookie, $template,
428 { module => 'cataloguing', record => $record } );
430 my $oldrecord = TransformMarcToKoha($record);
431 my $itemrecord;
432 my $nextop="additem";
433 my @errors; # store errors found while checking data BEFORE saving item.
435 # Getting last created item cookie
436 my $prefillitem = C4::Context->preference('PrefillItem');
437 my $justaddeditem;
438 my $cookieitemrecord;
439 if ($prefillitem) {
440 my $lastitemcookie = $input->cookie('LastCreatedItem');
441 if ($lastitemcookie) {
442 $lastitemcookie = uri_unescape($lastitemcookie);
443 eval {
444 if ( thaw($lastitemcookie) ) {
445 $cookieitemrecord = thaw($lastitemcookie);
446 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
449 if ($@) {
450 $lastitemcookie = 'undef' unless $lastitemcookie;
451 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
456 #-------------------------------------------------------------------------------
457 if ($op eq "additem") {
459 #-------------------------------------------------------------------------------
460 # rebuild
461 my @tags = $input->multi_param('tag');
462 my @subfields = $input->multi_param('subfield');
463 my @values = $input->multi_param('field_value');
464 # build indicator hash.
465 my @ind_tag = $input->multi_param('ind_tag');
466 my @indicator = $input->multi_param('indicator');
467 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
468 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
470 # type of add
471 my $add_submit = $input->param('add_submit');
472 my $add_duplicate_submit = $input->param('add_duplicate_submit');
473 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
474 my $number_of_copies = $input->param('number_of_copies');
476 # This is a bit tricky : if there is a cookie for the last created item and
477 # we just added an item, the cookie value is not correct yet (it will be updated
478 # next page). To prevent the form from being filled with outdated values, we
479 # force the use of "add and duplicate" feature, so the form will be filled with
480 # correct values.
481 $add_duplicate_submit = 1 if ($prefillitem);
482 $justaddeditem = 1;
484 # if autoBarcode is set to 'incremental', calculate barcode...
485 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
486 $record = _increment_barcode($record, $frameworkcode);
489 my $addedolditem = TransformMarcToKoha( $record );
491 # If we have to add or add & duplicate, we add the item
492 if ( $add_submit || $add_duplicate_submit ) {
494 # check for item barcode # being unique
495 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
496 push @errors, "barcode_not_unique" if ($exist_itemnumber);
498 # if barcode exists, don't create, but report The problem.
499 unless ($exist_itemnumber) {
500 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
501 set_item_default_location($oldbibitemnum);
503 # Pushing the last created item cookie back
504 if ($prefillitem && defined $record) {
505 my $itemcookie = $input->cookie(
506 -name => 'LastCreatedItem',
507 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
508 -value => uri_escape_utf8( freeze( $record ) ),
509 -HttpOnly => 1,
510 -expires => ''
513 $cookie = [ $cookie, $itemcookie ];
517 $nextop = "additem";
518 if ($exist_itemnumber) {
519 $itemrecord = $record;
523 # If we have to add & duplicate
524 if ($add_duplicate_submit) {
525 $itemrecord = $record;
526 if (C4::Context->preference('autoBarcode') eq 'incremental') {
527 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
529 else {
530 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
531 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
532 my $fieldItem = $itemrecord->field($tagfield);
533 $itemrecord->delete_field($fieldItem);
534 $fieldItem->delete_subfields($tagsubfield);
535 $itemrecord->insert_fields_ordered($fieldItem);
537 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
540 # If we have to add multiple copies
541 if ($add_multiple_copies_submit) {
543 use C4::Barcodes;
544 my $barcodeobj = C4::Barcodes->new;
545 my $copynumber = $addedolditem->{'copynumber'};
546 my $oldbarcode = $addedolditem->{'barcode'};
547 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
548 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
550 # If there is a barcode and we can't find their new values, we can't add multiple copies
551 my $testbarcode;
552 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
553 if ($oldbarcode && !$testbarcode) {
555 push @errors, "no_next_barcode";
556 $itemrecord = $record;
558 } else {
559 # We add each item
561 # For the first iteration
562 my $barcodevalue = $oldbarcode;
563 my $exist_itemnumber;
566 for (my $i = 0; $i < $number_of_copies;) {
568 # If there is a barcode
569 if ($barcodevalue) {
571 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
572 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
574 # Putting it into the record
575 if ($barcodevalue) {
576 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
577 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
578 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
579 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
580 # But when adding multiple copies we need to prefix it here,
581 # so we retrieve the homebranch from the item and prefix the barcode with it.
582 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
583 my $homebranch = $record->subfield($hb_field, $hb_subfield);
584 $barcodevalue = $homebranch . $barcodevalue;
586 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
589 # Checking if the barcode already exists
590 $exist_itemnumber = get_item_from_barcode($barcodevalue);
592 # Updating record with the new copynumber
593 if ( $copynumber ){
594 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
597 # Adding the item
598 if (!$exist_itemnumber) {
599 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
600 set_item_default_location($oldbibitemnum);
602 # We count the item only if it was really added
603 # That way, all items are added, even if there was some already existing barcodes
604 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
605 $i++;
606 # Only increment copynumber if item was really added
607 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
610 # Preparing the next iteration
611 $oldbarcode = $barcodevalue;
613 undef($itemrecord);
616 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
617 print $input->redirect(
618 '/cgi-bin/koha/circ/circulation.pl?'
619 .'borrowernumber='.$fa_circborrowernumber
620 .'&barcode='.uri_escape_utf8($fa_barcode)
621 .'&duedatespec='.$fa_duedatespec
622 .'&stickyduedate=1'
624 exit;
628 #-------------------------------------------------------------------------------
629 } elsif ($op eq "edititem") {
630 #-------------------------------------------------------------------------------
631 # retrieve item if exist => then, it's a modif
632 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
633 $nextop = "saveitem";
634 #-------------------------------------------------------------------------------
635 } elsif ($op eq "dupeitem") {
636 #-------------------------------------------------------------------------------
637 # retrieve item if exist => then, it's a modif
638 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
639 if (C4::Context->preference('autoBarcode') eq 'incremental') {
640 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
642 else {
643 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
644 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
645 my $fieldItem = $itemrecord->field($tagfield);
646 $itemrecord->delete_field($fieldItem);
647 $fieldItem->delete_subfields($tagsubfield);
648 $itemrecord->insert_fields_ordered($fieldItem);
651 #check for hidden subfield and remove them for the duplicated item
652 foreach my $field ($itemrecord->fields()){
653 my $tag = $field->{_tag};
654 foreach my $subfield ($field->subfields()){
655 my $subfieldtag = $subfield->[0];
656 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
657 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
658 my $fieldItem = $itemrecord->field($tag);
659 $itemrecord->delete_field($fieldItem);
660 $fieldItem->delete_subfields($subfieldtag);
661 $itemrecord->insert_fields_ordered($fieldItem);
666 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
667 $nextop = "additem";
668 #-------------------------------------------------------------------------------
669 } elsif ($op eq "delitem") {
670 #-------------------------------------------------------------------------------
671 # check that there is no issue on this item before deletion.
672 my $item = Koha::Items->find($itemnumber);
673 $error = $item->safe_delete;
674 if($error ne '1'){
675 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
676 }else{
677 push @errors,$error;
678 $nextop="additem";
680 #-------------------------------------------------------------------------------
681 } elsif ($op eq "delallitems") {
682 #-------------------------------------------------------------------------------
683 my $items = Koha::Items->search({ biblionumber => $biblionumber });
684 while ( my $item = $items->next ) {
685 $error = $item->safe_delete;
686 next if $error eq '1'; # Means ok
687 push @errors,$error;
689 if ( @errors ) {
690 $nextop="additem";
691 } else {
692 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
693 my $views = { C4::Search::enabled_staff_search_views };
694 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
695 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
696 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
697 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
698 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
699 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
700 } else {
701 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
703 exit;
705 #-------------------------------------------------------------------------------
706 } elsif ($op eq "saveitem") {
707 #-------------------------------------------------------------------------------
708 # rebuild
709 my @tags = $input->multi_param('tag');
710 my @subfields = $input->multi_param('subfield');
711 my @values = $input->multi_param('field_value');
712 # build indicator hash.
713 my @ind_tag = $input->multi_param('ind_tag');
714 my @indicator = $input->multi_param('indicator');
715 # my $itemnumber = $input->param('itemnumber');
716 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
717 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
718 # MARC::Record builded => now, record in DB
719 # warn "R: ".$record->as_formatted;
720 # check that the barcode don't exist already
721 my $addedolditem = TransformMarcToKoha($itemtosave);
722 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
723 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
724 push @errors,"barcode_not_unique";
725 } else {
726 my $item = Koha::Items->find($itemnumber );
727 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
728 $itemnumber = q{};
729 my $olditemlost = $item->itemlost;
730 my $newitemlost = $newitem->{itemlost};
731 LostItem( $item->itemnumber, 'additem' )
732 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
734 $nextop="additem";
735 } elsif ($op eq "delinkitem"){
736 my $analyticfield = '773';
737 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
738 $analyticfield = '773';
739 } elsif ($marcflavour eq 'UNIMARC') {
740 $analyticfield = '461';
742 foreach my $field ($record->field($analyticfield)){
743 if ($field->subfield('9') eq $hostitemnumber){
744 $record->delete_field($field);
745 last;
748 my $modbibresult = ModBiblio($record, $biblionumber,'');
752 #-------------------------------------------------------------------------------
753 # build screen with existing items. and "new" one
754 #-------------------------------------------------------------------------------
756 # now, build existiing item list
757 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
758 #my @fields = $record->fields();
761 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
762 my @big_array;
763 #---- finds where items.itemnumber is stored
764 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
765 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
766 C4::Biblio::EmbedItemsInMarcBiblio({
767 marc_record => $temp,
768 biblionumber => $biblionumber });
769 my @fields = $temp->fields();
772 my @hostitemnumbers;
773 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
774 my $analyticfield = '773';
775 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
776 $analyticfield = '773';
777 } elsif ($marcflavour eq 'UNIMARC') {
778 $analyticfield = '461';
780 foreach my $hostfield ($temp->field($analyticfield)){
781 my $hostbiblionumber = $hostfield->subfield('0');
782 if ($hostbiblionumber){
783 my $hostrecord = GetMarcBiblio({
784 biblionumber => $hostbiblionumber,
785 embed_items => 1 });
786 if ($hostrecord) {
787 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
788 foreach my $hostitem ($hostrecord->field($itemfield)){
789 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
790 push (@fields, $hostitem);
791 push (@hostitemnumbers, $hostfield->subfield('9'));
799 foreach my $field (@fields) {
800 next if ( $field->tag() < 10 );
802 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
803 my %this_row;
804 # loop through each subfield
805 my $i = 0;
806 foreach my $subfield (@subf){
807 my $subfieldcode = $subfield->[0];
808 my $subfieldvalue= $subfield->[1];
810 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
811 && ($field->tag() ne $itemtagfield
812 && $subfieldcode ne $itemtagsubfield));
813 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
814 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
815 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
816 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
817 $subfieldcode, $subfieldvalue, '', $tagslib)
818 || $subfieldvalue;
821 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
822 #verifying rights
823 my $userenv = C4::Context->userenv();
824 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
825 $this_row{'nomod'} = 1;
828 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
830 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
831 foreach my $hostitemnumber (@hostitemnumbers) {
832 my $item = Koha::Items->find( $hostitemnumber );
833 if ($this_row{itemnumber} eq $hostitemnumber) {
834 $this_row{hostitemflag} = 1;
835 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
836 last;
841 if (%this_row) {
842 push(@big_array, \%this_row);
846 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
847 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
849 # now, construct template !
850 # First, the existing items for display
851 my @item_value_loop;
852 my @header_value_loop;
853 for my $row ( @big_array ) {
854 my %row_data;
855 my @item_fields;
856 foreach my $key (sort keys %witness){
857 my $item_field;
858 if ( $row->{$key} ){
859 $item_field->{field} = $row->{$key};
860 } else {
861 $item_field->{field} = '';
864 for my $kohafield (
865 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
868 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
869 next unless $key eq $subfield;
870 $item_field->{field} = output_pref( { str => $row->{$key}, dateonly => 1 } );
873 push @item_fields, $item_field;
875 $row_data{item_value} = [ @item_fields ];
876 $row_data{itemnumber} = $row->{itemnumber};
877 #reporting this_row values
878 $row_data{'nomod'} = $row->{'nomod'};
879 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
880 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
881 # $row_data{'countanalytics'} = $row->{'countanalytics'};
882 push(@item_value_loop,\%row_data);
884 foreach my $subfield_code (sort keys(%witness)) {
885 my %header_value;
886 $header_value{header_value} = $witness{$subfield_code};
888 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
889 my $kohafield = $subfieldlib->{kohafield};
890 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
891 $header_value{column_name} = $1;
894 push(@header_value_loop, \%header_value);
897 # now, build the item form for entering a new item
898 my @loop_data =();
899 my $i=0;
901 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
902 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
903 for my $library ( @$libraries ) {
904 $library->{selected} = 1 if $library->{branchcode} eq $branch
907 # We generate form, from actuel record
908 @fields = ();
909 if($itemrecord){
910 foreach my $field ($itemrecord->fields()){
911 my $tag = $field->{_tag};
912 foreach my $subfield ( $field->subfields() ){
914 my $subfieldtag = $subfield->[0];
915 my $value = $subfield->[1];
916 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
918 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
920 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
921 push @fields, "$tag$subfieldtag";
922 push (@loop_data, $subfield_data);
923 $i++;
928 # and now we add fields that are empty
930 # Using last created item if it exists
932 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
934 # We generate form, and fill with values if defined
935 foreach my $tag ( keys %{$tagslib}){
936 foreach my $subtag (keys %{$tagslib->{$tag}}){
937 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
938 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
939 next if any { /^$tag$subtag$/ } @fields;
941 my @values = (undef);
942 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
943 for my $value (@values){
944 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
945 push (@loop_data, $subfield_data);
946 $i++;
950 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
952 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
954 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
955 $template->param(
956 biblionumber => $biblionumber,
957 title => $oldrecord->{title},
958 author => $oldrecord->{author},
959 item_loop => \@item_value_loop,
960 item_header_loop => \@header_value_loop,
961 item => \@loop_data,
962 itemnumber => $itemnumber,
963 barcode => $item ? $item->barcode : undef,
964 itemtagfield => $itemtagfield,
965 itemtagsubfield => $itemtagsubfield,
966 op => $nextop,
967 popup => scalar $input->param('popup') ? 1: 0,
968 C4::Search::enabled_staff_search_views,
970 $template->{'VARS'}->{'searchid'} = $searchid;
972 if ($frameworkcode eq 'FA'){
973 # fast cataloguing datas
974 $template->param(
975 'circborrowernumber' => $fa_circborrowernumber,
976 'barcode' => $fa_barcode,
977 'branch' => $fa_branch,
978 'stickyduedate' => $fa_stickyduedate,
979 'duedatespec' => $fa_duedatespec,
983 foreach my $error (@errors) {
984 $template->param($error => 1);
986 output_html_with_http_headers $input, $cookie, $template->output;