Bug 3137: (follow-up) Rename using 'collapse', remove syspref lettering and fix guara...
[koha.git] / cataloguing / additem.pl
blob0bfeae72f578c60fd253047fd09357adab0904b8
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 ModItem(
81 permanent_location => $item->location,
82 location => C4::Context->preference('NewItemsDefaultLocation')
84 undef,
85 $itemnumber
88 else {
89 ModItem( { permanent_location => $item->location }, undef, $itemnumber )
90 unless defined $item->permanent_location;
94 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
95 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
96 sub _increment_barcode {
97 my ($record, $frameworkcode) = @_;
98 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
99 unless ($record->field($tagfield)->subfield($tagsubfield)) {
100 my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
101 $sth_barcode->execute;
102 my ($newbarcode) = $sth_barcode->fetchrow;
103 $newbarcode++;
104 # OK, we have the new barcode, now create the entry in MARC record
105 my $fieldItem = $record->field($tagfield);
106 $record->delete_field($fieldItem);
107 $fieldItem->add_subfields($tagsubfield => $newbarcode);
108 $record->insert_fields_ordered($fieldItem);
110 return $record;
114 sub generate_subfield_form {
115 my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $biblionumber, $temp, $loop_data, $i, $restrictededition) = @_;
117 my $frameworkcode = &GetFrameworkCode($biblionumber);
119 my %subfield_data;
120 my $dbh = C4::Context->dbh;
122 my $index_subfield = int(rand(1000000));
123 if ($subfieldtag eq '@'){
124 $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
125 } else {
126 $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
129 $subfield_data{tag} = $tag;
130 $subfield_data{subfield} = $subfieldtag;
131 $subfield_data{marc_lib} ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
132 $subfield_data{mandatory} = $subfieldlib->{mandatory};
133 $subfield_data{important} = $subfieldlib->{important};
134 $subfield_data{repeatable} = $subfieldlib->{repeatable};
135 $subfield_data{maxlength} = $subfieldlib->{maxlength};
137 if ( ! defined( $value ) || $value eq '') {
138 $value = $subfieldlib->{defaultvalue};
139 if ( $value ) {
140 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
141 my $today_dt = dt_from_string;
142 my $year = $today_dt->strftime('%Y');
143 my $month = $today_dt->strftime('%m');
144 my $day = $today_dt->strftime('%d');
145 $value =~ s/<<YYYY>>/$year/g;
146 $value =~ s/<<MM>>/$month/g;
147 $value =~ s/<<DD>>/$day/g;
148 # And <<USER>> with surname (?)
149 my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian");
150 $value=~s/<<USER>>/$username/g;
154 $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} <= -4));
156 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
157 if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
158 foreach my $pref_itemcallnumber_part (split(/,/, $pref_itemcallnumber)){
159 my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number
160 my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields
161 my $temp2 = $temp->field($CNtag);
163 next unless $temp2;
164 $value = $temp2->as_string( $CNsubfields, ' ' );
165 last if $value;
169 if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
170 my $input = new CGI;
171 $value = $input->param('barcode');
174 if ( $subfieldlib->{authorised_value} ) {
175 my @authorised_values;
176 my %authorised_lib;
177 # builds list, depending on authorised value...
178 if ( $subfieldlib->{authorised_value} eq "branches" ) {
179 foreach my $thisbranch (@$branches) {
180 push @authorised_values, $thisbranch->{branchcode};
181 $authorised_lib{$thisbranch->{branchcode}} = $thisbranch->{branchname};
182 $value = $thisbranch->{branchcode} if $thisbranch->{selected} && !$value;
185 elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
186 push @authorised_values, "";
187 my $branch_limit = C4::Context->userenv && C4::Context->userenv->{"branch"};
188 my $itemtypes;
189 if($branch_limit) {
190 $itemtypes = Koha::ItemTypes->search_with_localization({branchcode => $branch_limit});
191 } else {
192 $itemtypes = Koha::ItemTypes->search_with_localization;
194 while ( my $itemtype = $itemtypes->next ) {
195 push @authorised_values, $itemtype->itemtype;
196 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
199 unless ( $value ) {
200 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
201 $itype_sth->execute( $biblionumber );
202 ( $value ) = $itype_sth->fetchrow_array;
205 #---- class_sources
207 elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
208 push @authorised_values, "";
210 my $class_sources = GetClassSources();
211 my $default_source = C4::Context->preference("DefaultClassificationSource");
213 foreach my $class_source (sort keys %$class_sources) {
214 next unless $class_sources->{$class_source}->{'used'} or
215 ($value and $class_source eq $value) or
216 ($class_source eq $default_source);
217 push @authorised_values, $class_source;
218 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
220 $value = $default_source unless ($value);
222 #---- "true" authorised value
224 else {
225 push @authorised_values, qq{};
226 my $av = GetAuthorisedValues( $subfieldlib->{authorised_value} );
227 for my $r ( @$av ) {
228 push @authorised_values, $r->{authorised_value};
229 $authorised_lib{$r->{authorised_value}} = $r->{lib};
233 if ( $subfieldlib->{hidden} > 4 or $subfieldlib->{hidden} <= -4 ) {
234 $subfield_data{marc_value} = {
235 type => 'hidden',
236 id => $subfield_data{id},
237 maxlength => $subfield_data{maxlength},
238 value => $value,
241 else {
242 $subfield_data{marc_value} = {
243 type => 'select',
244 id => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
245 values => \@authorised_values,
246 labels => \%authorised_lib,
247 default => $value,
251 # it's a thesaurus / authority field
252 elsif ( $subfieldlib->{authtypecode} ) {
253 $subfield_data{marc_value} = {
254 type => 'text_auth',
255 id => $subfield_data{id},
256 maxlength => $subfield_data{maxlength},
257 value => $value,
258 authtypecode => $subfieldlib->{authtypecode},
261 # it's a plugin field
262 elsif ( $subfieldlib->{value_builder} ) { # plugin
263 require Koha::FrameworkPlugin;
264 my $plugin = Koha::FrameworkPlugin->new({
265 name => $subfieldlib->{'value_builder'},
266 item_style => 1,
268 my $pars= { dbh => $dbh, record => $temp, tagslib =>$tagslib,
269 id => $subfield_data{id}, tabloop => $loop_data };
270 $plugin->build( $pars );
271 if( !$plugin->errstr ) {
272 my $class= 'buttonDot'. ( $plugin->noclick? ' disabled': '' );
273 $subfield_data{marc_value} = {
274 type => 'text_plugin',
275 id => $subfield_data{id},
276 maxlength => $subfield_data{maxlength},
277 value => $value,
278 class => $class,
279 nopopup => $plugin->noclick,
280 javascript => $plugin->javascript,
282 } else {
283 warn $plugin->errstr;
284 $subfield_data{marc_value} = {
285 type => 'text',
286 id => $subfield_data{id},
287 maxlength => $subfield_data{maxlength},
288 value => $value,
289 }; # supply default input form
292 elsif ( $tag eq '' ) { # it's an hidden field
293 $subfield_data{marc_value} = {
294 type => 'hidden',
295 id => $subfield_data{id},
296 maxlength => $subfield_data{maxlength},
297 value => $value,
300 elsif ( $subfieldlib->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
301 $subfield_data{marc_value} = {
302 type => 'text',
303 id => $subfield_data{id},
304 maxlength => $subfield_data{maxlength},
305 value => $value,
308 elsif (
310 $value and length($value) > 100
312 or (
313 C4::Context->preference("marcflavour") eq "UNIMARC"
314 and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a'
316 or (
317 C4::Context->preference("marcflavour") eq "MARC21"
318 and 500 <= $tag && $tag < 600
321 # oversize field (textarea)
322 $subfield_data{marc_value} = {
323 type => 'textarea',
324 id => $subfield_data{id},
325 value => $value,
327 } else {
328 # it's a standard field
329 $subfield_data{marc_value} = {
330 type => 'text',
331 id => $subfield_data{id},
332 maxlength => $subfield_data{maxlength},
333 value => $value,
337 # Getting list of subfields to keep when restricted editing is enabled
338 my $subfieldsToAllowForRestrictedEditing = C4::Context->preference('SubfieldsToAllowForRestrictedEditing');
339 my $allowAllSubfields = (
340 not defined $subfieldsToAllowForRestrictedEditing
341 or $subfieldsToAllowForRestrictedEditing eq q||
342 ) ? 1 : 0;
343 my @subfieldsToAllow = split(/ /, $subfieldsToAllowForRestrictedEditing);
345 # If we're on restricted editing, and our field is not in the list of subfields to allow,
346 # then it is read-only
347 $subfield_data{marc_value}->{readonly} = (
348 not $allowAllSubfields
349 and $restrictededition
350 and !grep { $tag . '$' . $subfieldtag eq $_ } @subfieldsToAllow
351 ) ? 1: 0;
353 return \%subfield_data;
356 # Removes some subfields when prefilling items
357 # This function will remove any subfield that is not in the SubfieldsToUseWhenPrefill syspref
358 sub removeFieldsForPrefill {
360 my $item = shift;
362 # Getting item tag
363 my ($tag, $subtag) = GetMarcFromKohaField( "items.barcode" );
365 # Getting list of subfields to keep
366 my $subfieldsToUseWhenPrefill = C4::Context->preference('SubfieldsToUseWhenPrefill');
368 # Removing subfields that are not in the syspref
369 if ($tag && $subfieldsToUseWhenPrefill) {
370 my $field = $item->field($tag);
371 my @subfieldsToUse= split(/ /,$subfieldsToUseWhenPrefill);
372 foreach my $subfield ($field->subfields()) {
373 if (!grep { $subfield->[0] eq $_ } @subfieldsToUse) {
374 $field->delete_subfield(code => $subfield->[0]);
380 return $item;
384 my $input = new CGI;
385 my $error = $input->param('error');
386 my $biblionumber = $input->param('biblionumber');
387 my $itemnumber = $input->param('itemnumber');
388 my $op = $input->param('op') || q{};
389 my $hostitemnumber = $input->param('hostitemnumber');
390 my $marcflavour = C4::Context->preference("marcflavour");
391 my $searchid = $input->param('searchid');
392 # fast cataloguing datas
393 my $fa_circborrowernumber = $input->param('circborrowernumber');
394 my $fa_barcode = $input->param('barcode');
395 my $fa_branch = $input->param('branch');
396 my $fa_stickyduedate = $input->param('stickyduedate');
397 my $fa_duedatespec = $input->param('duedatespec');
399 my $frameworkcode = &GetFrameworkCode($biblionumber);
401 # Defining which userflag is needing according to the framework currently used
402 my $userflags;
403 if (defined $input->param('frameworkcode')) {
404 $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
407 if (not defined $userflags) {
408 $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
411 my ($template, $loggedinuser, $cookie)
412 = get_template_and_user({template_name => "cataloguing/additem.tt",
413 query => $input,
414 type => "intranet",
415 authnotrequired => 0,
416 flagsrequired => {editcatalogue => $userflags},
417 debug => 1,
421 # Does the user have a restricted item editing permission?
422 my $uid = Koha::Patrons->find( $loggedinuser )->userid;
423 my $restrictededition = $uid ? haspermission($uid, {'editcatalogue' => 'edit_items_restricted'}) : undef;
424 # In case user is a superlibrarian, editing is not restricted
425 $restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian());
426 # In case user has fast cataloging permission (and we're in fast cataloging), editing is not restricted
427 $restrictededition = 0 if ($restrictededition != 0 && $frameworkcode eq 'FA' && haspermission($uid, {'editcatalogue' => 'fast_cataloging'}));
429 my $tagslib = &GetMarcStructure(1,$frameworkcode);
430 my $record = GetMarcBiblio({ biblionumber => $biblionumber });
432 output_and_exit_if_error( $input, $cookie, $template,
433 { module => 'cataloguing', record => $record } );
435 my $oldrecord = TransformMarcToKoha($record);
436 my $itemrecord;
437 my $nextop="additem";
438 my @errors; # store errors found while checking data BEFORE saving item.
440 # Getting last created item cookie
441 my $prefillitem = C4::Context->preference('PrefillItem');
442 my $justaddeditem;
443 my $cookieitemrecord;
444 if ($prefillitem) {
445 my $lastitemcookie = $input->cookie('LastCreatedItem');
446 if ($lastitemcookie) {
447 $lastitemcookie = uri_unescape($lastitemcookie);
448 eval {
449 if ( thaw($lastitemcookie) ) {
450 $cookieitemrecord = thaw($lastitemcookie);
451 $cookieitemrecord = removeFieldsForPrefill($cookieitemrecord);
454 if ($@) {
455 $lastitemcookie = 'undef' unless $lastitemcookie;
456 warn "Storable::thaw failed to thaw LastCreatedItem-cookie. Cookie value '$lastitemcookie'. Caught error follows: '$@'";
461 #-------------------------------------------------------------------------------
462 if ($op eq "additem") {
464 #-------------------------------------------------------------------------------
465 # rebuild
466 my @tags = $input->multi_param('tag');
467 my @subfields = $input->multi_param('subfield');
468 my @values = $input->multi_param('field_value');
469 # build indicator hash.
470 my @ind_tag = $input->multi_param('ind_tag');
471 my @indicator = $input->multi_param('indicator');
472 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
473 my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
475 # type of add
476 my $add_submit = $input->param('add_submit');
477 my $add_duplicate_submit = $input->param('add_duplicate_submit');
478 my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
479 my $number_of_copies = $input->param('number_of_copies');
481 # This is a bit tricky : if there is a cookie for the last created item and
482 # we just added an item, the cookie value is not correct yet (it will be updated
483 # next page). To prevent the form from being filled with outdated values, we
484 # force the use of "add and duplicate" feature, so the form will be filled with
485 # correct values.
486 $add_duplicate_submit = 1 if ($prefillitem);
487 $justaddeditem = 1;
489 # if autoBarcode is set to 'incremental', calculate barcode...
490 if ( C4::Context->preference('autoBarcode') eq 'incremental' ) {
491 $record = _increment_barcode($record, $frameworkcode);
494 my $addedolditem = TransformMarcToKoha( $record );
496 # If we have to add or add & duplicate, we add the item
497 if ( $add_submit || $add_duplicate_submit ) {
499 # check for item barcode # being unique
500 my $exist_itemnumber = get_item_from_barcode( $addedolditem->{'barcode'} );
501 push @errors, "barcode_not_unique" if ($exist_itemnumber);
503 # if barcode exists, don't create, but report The problem.
504 unless ($exist_itemnumber) {
505 my ( $oldbiblionumber, $oldbibnum, $oldbibitemnum ) = AddItemFromMarc( $record, $biblionumber );
506 set_item_default_location($oldbibitemnum);
508 # Pushing the last created item cookie back
509 if ($prefillitem && defined $record) {
510 my $itemcookie = $input->cookie(
511 -name => 'LastCreatedItem',
512 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
513 -value => uri_escape_utf8( freeze( $record ) ),
514 -HttpOnly => 1,
515 -expires => ''
518 $cookie = [ $cookie, $itemcookie ];
522 $nextop = "additem";
523 if ($exist_itemnumber) {
524 $itemrecord = $record;
528 # If we have to add & duplicate
529 if ($add_duplicate_submit) {
530 $itemrecord = $record;
531 if (C4::Context->preference('autoBarcode') eq 'incremental') {
532 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
534 else {
535 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
536 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
537 my $fieldItem = $itemrecord->field($tagfield);
538 $itemrecord->delete_field($fieldItem);
539 $fieldItem->delete_subfields($tagsubfield);
540 $itemrecord->insert_fields_ordered($fieldItem);
542 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
545 # If we have to add multiple copies
546 if ($add_multiple_copies_submit) {
548 use C4::Barcodes;
549 my $barcodeobj = C4::Barcodes->new;
550 my $copynumber = $addedolditem->{'copynumber'};
551 my $oldbarcode = $addedolditem->{'barcode'};
552 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
553 my ($copytagfield,$copytagsubfield) = &GetMarcFromKohaField( "items.copynumber" );
555 # If there is a barcode and we can't find their new values, we can't add multiple copies
556 my $testbarcode;
557 $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
558 if ($oldbarcode && !$testbarcode) {
560 push @errors, "no_next_barcode";
561 $itemrecord = $record;
563 } else {
564 # We add each item
566 # For the first iteration
567 my $barcodevalue = $oldbarcode;
568 my $exist_itemnumber;
571 for (my $i = 0; $i < $number_of_copies;) {
573 # If there is a barcode
574 if ($barcodevalue) {
576 # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
577 $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
579 # Putting it into the record
580 if ($barcodevalue) {
581 if ( C4::Context->preference("autoBarcode") eq 'hbyymmincr' && $i > 0 ) { # The first copy already contains the homebranch prefix
582 # This is terribly hacky but the easiest way to fix the way hbyymmincr is working
583 # Contrary to what one might think, the barcode plugin does not prefix the returned string with the homebranch
584 # For a single item, it is handled with some JS code (see cataloguing/value_builder/barcode.pl)
585 # But when adding multiple copies we need to prefix it here,
586 # so we retrieve the homebranch from the item and prefix the barcode with it.
587 my ($hb_field, $hb_subfield) = GetMarcFromKohaField( "items.homebranch" );
588 my $homebranch = $record->subfield($hb_field, $hb_subfield);
589 $barcodevalue = $homebranch . $barcodevalue;
591 $record->field($tagfield)->update($tagsubfield => $barcodevalue);
594 # Checking if the barcode already exists
595 $exist_itemnumber = get_item_from_barcode($barcodevalue);
597 # Updating record with the new copynumber
598 if ( $copynumber ){
599 $record->field($copytagfield)->update($copytagsubfield => $copynumber);
602 # Adding the item
603 if (!$exist_itemnumber) {
604 my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
605 set_item_default_location($oldbibitemnum);
607 # We count the item only if it was really added
608 # That way, all items are added, even if there was some already existing barcodes
609 # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
610 $i++;
611 # Only increment copynumber if item was really added
612 $copynumber++ if ( $copynumber && $copynumber =~ m/^\d+$/ );
615 # Preparing the next iteration
616 $oldbarcode = $barcodevalue;
618 undef($itemrecord);
621 if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
622 print $input->redirect(
623 '/cgi-bin/koha/circ/circulation.pl?'
624 .'borrowernumber='.$fa_circborrowernumber
625 .'&barcode='.uri_escape_utf8($fa_barcode)
626 .'&duedatespec='.$fa_duedatespec
627 .'&stickyduedate=1'
629 exit;
633 #-------------------------------------------------------------------------------
634 } elsif ($op eq "edititem") {
635 #-------------------------------------------------------------------------------
636 # retrieve item if exist => then, it's a modif
637 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
638 $nextop = "saveitem";
639 #-------------------------------------------------------------------------------
640 } elsif ($op eq "dupeitem") {
641 #-------------------------------------------------------------------------------
642 # retrieve item if exist => then, it's a modif
643 $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
644 if (C4::Context->preference('autoBarcode') eq 'incremental') {
645 $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
647 else {
648 # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
649 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField( "items.barcode" );
650 my $fieldItem = $itemrecord->field($tagfield);
651 $itemrecord->delete_field($fieldItem);
652 $fieldItem->delete_subfields($tagsubfield);
653 $itemrecord->insert_fields_ordered($fieldItem);
656 #check for hidden subfield and remove them for the duplicated item
657 foreach my $field ($itemrecord->fields()){
658 my $tag = $field->{_tag};
659 foreach my $subfield ($field->subfields()){
660 my $subfieldtag = $subfield->[0];
661 if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10"
662 || abs($tagslib->{$tag}->{$subfieldtag}->{hidden})>4 ){
663 my $fieldItem = $itemrecord->field($tag);
664 $itemrecord->delete_field($fieldItem);
665 $fieldItem->delete_subfields($subfieldtag);
666 $itemrecord->insert_fields_ordered($fieldItem);
671 $itemrecord = removeFieldsForPrefill($itemrecord) if ($prefillitem);
672 $nextop = "additem";
673 #-------------------------------------------------------------------------------
674 } elsif ($op eq "delitem") {
675 #-------------------------------------------------------------------------------
676 # check that there is no issue on this item before deletion.
677 $error = &DelItemCheck( $biblionumber,$itemnumber);
678 if($error == 1){
679 print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid");
680 }else{
681 push @errors,$error;
682 $nextop="additem";
684 #-------------------------------------------------------------------------------
685 } elsif ($op eq "delallitems") {
686 #-------------------------------------------------------------------------------
687 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber })->get_column('itemnumber');
688 foreach my $itemnumber ( @itemnumbers ) {
689 $error = C4::Items::DelItemCheck( $biblionumber, $itemnumber );
690 next if $error == 1; # Means ok
691 push @errors,$error;
693 if ( @errors ) {
694 $nextop="additem";
695 } else {
696 my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
697 my $views = { C4::Search::enabled_staff_search_views };
698 if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
699 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
700 } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) {
701 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
702 } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
703 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid");
704 } else {
705 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid");
707 exit;
709 #-------------------------------------------------------------------------------
710 } elsif ($op eq "saveitem") {
711 #-------------------------------------------------------------------------------
712 # rebuild
713 my @tags = $input->multi_param('tag');
714 my @subfields = $input->multi_param('subfield');
715 my @values = $input->multi_param('field_value');
716 # build indicator hash.
717 my @ind_tag = $input->multi_param('ind_tag');
718 my @indicator = $input->multi_param('indicator');
719 # my $itemnumber = $input->param('itemnumber');
720 my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
721 my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
722 # MARC::Record builded => now, record in DB
723 # warn "R: ".$record->as_formatted;
724 # check that the barcode don't exist already
725 my $addedolditem = TransformMarcToKoha($itemtosave);
726 my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
727 if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
728 push @errors,"barcode_not_unique";
729 } else {
730 my $item = Koha::Items->find($itemnumber );
731 my $newitem = ModItemFromMarc($itemtosave, $biblionumber, $itemnumber);
732 $itemnumber = q{};
733 my $olditemlost = $item->itemlost;
734 my $newitemlost = $newitem->{itemlost};
735 LostItem( $item->itemnumber, 'additem' )
736 if $newitemlost && $newitemlost ge '1' && !$olditemlost;
738 $nextop="additem";
739 } elsif ($op eq "delinkitem"){
740 my $analyticfield = '773';
741 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC'){
742 $analyticfield = '773';
743 } elsif ($marcflavour eq 'UNIMARC') {
744 $analyticfield = '461';
746 foreach my $field ($record->field($analyticfield)){
747 if ($field->subfield('9') eq $hostitemnumber){
748 $record->delete_field($field);
749 last;
752 my $modbibresult = ModBiblio($record, $biblionumber,'');
756 #-------------------------------------------------------------------------------
757 # build screen with existing items. and "new" one
758 #-------------------------------------------------------------------------------
760 # now, build existiing item list
761 my $temp = GetMarcBiblio({ biblionumber => $biblionumber });
762 #my @fields = $record->fields();
765 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
766 my @big_array;
767 #---- finds where items.itemnumber is stored
768 my ( $itemtagfield, $itemtagsubfield) = &GetMarcFromKohaField( "items.itemnumber" );
769 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField( "items.homebranch" );
770 C4::Biblio::EmbedItemsInMarcBiblio({
771 marc_record => $temp,
772 biblionumber => $biblionumber });
773 my @fields = $temp->fields();
776 my @hostitemnumbers;
777 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
778 my $analyticfield = '773';
779 if ($marcflavour eq 'MARC21' || $marcflavour eq 'NORMARC') {
780 $analyticfield = '773';
781 } elsif ($marcflavour eq 'UNIMARC') {
782 $analyticfield = '461';
784 foreach my $hostfield ($temp->field($analyticfield)){
785 my $hostbiblionumber = $hostfield->subfield('0');
786 if ($hostbiblionumber){
787 my $hostrecord = GetMarcBiblio({
788 biblionumber => $hostbiblionumber,
789 embed_items => 1 });
790 if ($hostrecord) {
791 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber' );
792 foreach my $hostitem ($hostrecord->field($itemfield)){
793 if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
794 push (@fields, $hostitem);
795 push (@hostitemnumbers, $hostfield->subfield('9'));
803 foreach my $field (@fields) {
804 next if ( $field->tag() < 10 );
806 my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
807 my %this_row;
808 # loop through each subfield
809 my $i = 0;
810 foreach my $subfield (@subf){
811 my $subfieldcode = $subfield->[0];
812 my $subfieldvalue= $subfield->[1];
814 next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10
815 && ($field->tag() ne $itemtagfield
816 && $subfieldcode ne $itemtagsubfield));
817 $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10);
818 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} eq 10) {
819 $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
820 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
821 $subfieldcode, $subfieldvalue, '', $tagslib)
822 || $subfieldvalue;
825 if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependentBranches")) {
826 #verifying rights
827 my $userenv = C4::Context->userenv();
828 unless (C4::Context->IsSuperLibrarian() or (($userenv->{'branch'} eq $subfieldvalue))){
829 $this_row{'nomod'} = 1;
832 $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
834 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
835 foreach my $hostitemnumber (@hostitemnumbers) {
836 my $item = Koha::Items->find( $hostitemnumber );
837 if ($this_row{itemnumber} eq $hostitemnumber) {
838 $this_row{hostitemflag} = 1;
839 $this_row{hostbiblionumber}= $item->biblio->biblionumber;
840 last;
845 if (%this_row) {
846 push(@big_array, \%this_row);
850 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" );
851 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
853 # now, construct template !
854 # First, the existing items for display
855 my @item_value_loop;
856 my @header_value_loop;
857 for my $row ( @big_array ) {
858 my %row_data;
859 my @item_fields;
860 foreach my $key (sort keys %witness){
861 my $item_field;
862 if ( $row->{$key} ){
863 $item_field->{field} = $row->{$key};
864 } else {
865 $item_field->{field} = '';
868 for my $kohafield (
869 qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate )
872 my ( undef, $subfield ) = GetMarcFromKohaField($kohafield);
873 next unless $key eq $subfield;
874 $item_field->{field} = output_pref( { str => $row->{$key}, dateonly => 1 } );
877 push @item_fields, $item_field;
879 $row_data{item_value} = [ @item_fields ];
880 $row_data{itemnumber} = $row->{itemnumber};
881 #reporting this_row values
882 $row_data{'nomod'} = $row->{'nomod'};
883 $row_data{'hostitemflag'} = $row->{'hostitemflag'};
884 $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
885 # $row_data{'countanalytics'} = $row->{'countanalytics'};
886 push(@item_value_loop,\%row_data);
888 foreach my $subfield_code (sort keys(%witness)) {
889 my %header_value;
890 $header_value{header_value} = $witness{$subfield_code};
892 my $subfieldlib = $tagslib->{$itemtagfield}->{$subfield_code};
893 my $kohafield = $subfieldlib->{kohafield};
894 if ( $kohafield && $kohafield =~ /items.(.+)/ ) {
895 $header_value{column_name} = $1;
898 push(@header_value_loop, \%header_value);
901 # now, build the item form for entering a new item
902 my @loop_data =();
903 my $i=0;
905 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
906 my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed;# build once ahead of time, instead of multiple times later.
907 for my $library ( @$libraries ) {
908 $library->{selected} = 1 if $library->{branchcode} eq $branch
911 # We generate form, from actuel record
912 @fields = ();
913 if($itemrecord){
914 foreach my $field ($itemrecord->fields()){
915 my $tag = $field->{_tag};
916 foreach my $subfield ( $field->subfields() ){
918 my $subfieldtag = $subfield->[0];
919 my $value = $subfield->[1];
920 my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
922 next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
924 my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
925 push @fields, "$tag$subfieldtag";
926 push (@loop_data, $subfield_data);
927 $i++;
932 # and now we add fields that are empty
934 # Using last created item if it exists
936 $itemrecord = $cookieitemrecord if ($prefillitem and not $justaddeditem and $op ne "edititem");
938 # We generate form, and fill with values if defined
939 foreach my $tag ( keys %{$tagslib}){
940 foreach my $subtag (keys %{$tagslib->{$tag}}){
941 next if IsMarcStructureInternal($tagslib->{$tag}{$subtag});
942 next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
943 next if any { /^$tag$subtag$/ } @fields;
945 my @values = (undef);
946 @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)) && defined($itemrecord->field($tag)->subfield($subtag)));
947 for my $value (@values){
948 my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $libraries, $biblionumber, $temp, \@loop_data, $i, $restrictededition);
949 push (@loop_data, $subfield_data);
950 $i++;
954 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
956 my $item = Koha::Items->find($itemnumber); # We certainly want to fetch it earlier
958 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
959 $template->param(
960 biblionumber => $biblionumber,
961 title => $oldrecord->{title},
962 author => $oldrecord->{author},
963 item_loop => \@item_value_loop,
964 item_header_loop => \@header_value_loop,
965 item => \@loop_data,
966 itemnumber => $itemnumber,
967 barcode => $item ? $item->barcode : undef,
968 itemtagfield => $itemtagfield,
969 itemtagsubfield => $itemtagsubfield,
970 op => $nextop,
971 popup => scalar $input->param('popup') ? 1: 0,
972 C4::Search::enabled_staff_search_views,
974 $template->{'VARS'}->{'searchid'} = $searchid;
976 if ($frameworkcode eq 'FA'){
977 # fast cataloguing datas
978 $template->param(
979 'circborrowernumber' => $fa_circborrowernumber,
980 'barcode' => $fa_barcode,
981 'branch' => $fa_branch,
982 'stickyduedate' => $fa_stickyduedate,
983 'duedatespec' => $fa_duedatespec,
987 foreach my $error (@errors) {
988 $template->param($error => 1);
990 output_html_with_http_headers $input, $cookie, $template->output;