Bug 10284: Add missing spaces between label and content in XSLT view (780/785)
[koha.git] / cataloguing / additem.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2004-2010 BibLibre
5 # Parts Copyright Catalyst IT 2011
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use CGI;
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Context;
30 use C4::Koha; # XXX subfield_is_koha_internal_p
31 use C4::Branch; # XXX subfield_is_koha_internal_p
32 use C4::ClassSource;
33 use C4::Dates;
34 use List::MoreUtils qw/any/;
35 use C4::Search;
36
37 use MARC::File::XML;
38 use URI::Escape;
39
40 my $dbh = C4::Context->dbh;
41
42 sub find_value {
43     my ($tagfield,$insubfield,$record) = @_;
44     my $result;
45     my $indicator;
46     foreach my $field ($record->field($tagfield)) {
47         my @subfields = $field->subfields();
48         foreach my $subfield (@subfields) {
49             if (@$subfield[0] eq $insubfield) {
50                 $result .= @$subfield[1];
51                 $indicator = $field->indicator(1).$field->indicator(2);
52             }
53         }
54     }
55     return($indicator,$result);
56 }
57
58 sub get_item_from_barcode {
59     my ($barcode)=@_;
60     my $dbh=C4::Context->dbh;
61     my $result;
62     my $rq=$dbh->prepare("SELECT itemnumber from items where items.barcode=?");
63     $rq->execute($barcode);
64     ($result)=$rq->fetchrow;
65     return($result);
66 }
67
68 sub set_item_default_location {
69     my $itemnumber = shift;
70     my $item = GetItem( $itemnumber );
71     if ( C4::Context->preference('NewItemsDefaultLocation') ) {
72         $item->{'permanent_location'} = $item->{'location'};
73         $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
74         ModItem( $item, undef, $itemnumber);
75     }
76     else {
77       $item->{'permanent_location'} = $item->{'location'} if !defined($item->{'permanent_location'});
78       ModItem( $item, undef, $itemnumber);
79     }
80 }
81
82 # NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
83 # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
84 sub _increment_barcode {
85     my ($record, $frameworkcode) = @_;
86     my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
87     unless ($record->field($tagfield)->subfield($tagsubfield)) {
88         my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
89         $sth_barcode->execute;
90         my ($newbarcode) = $sth_barcode->fetchrow;
91         $newbarcode++;
92         # OK, we have the new barcode, now create the entry in MARC record
93         my $fieldItem = $record->field($tagfield);
94         $record->delete_field($fieldItem);
95         $fieldItem->add_subfields($tagsubfield => $newbarcode);
96         $record->insert_fields_ordered($fieldItem);
97     }
98     return $record;
99 }
100
101
102 sub generate_subfield_form {
103         my ($tag, $subfieldtag, $value, $tagslib,$subfieldlib, $branches, $today_iso, $biblionumber, $temp, $loop_data, $i) = @_;
104   
105   my $frameworkcode = &GetFrameworkCode($biblionumber);
106         my %subfield_data;
107         my $dbh = C4::Context->dbh;        
108         my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
109         
110         my $index_subfield = int(rand(1000000)); 
111         if ($subfieldtag eq '@'){
112             $subfield_data{id} = "tag_".$tag."_subfield_00_".$index_subfield;
113         } else {
114             $subfield_data{id} = "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield;
115         }
116         
117         $subfield_data{tag}        = $tag;
118         $subfield_data{subfield}   = $subfieldtag;
119         $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
120         $subfield_data{marc_lib}   ="<span id=\"error$i\" title=\"".$subfieldlib->{lib}."\">".$subfieldlib->{lib}."</span>";
121         $subfield_data{mandatory}  = $subfieldlib->{mandatory};
122         $subfield_data{repeatable} = $subfieldlib->{repeatable};
123         $subfield_data{maxlength}  = $subfieldlib->{maxlength};
124         
125         $value =~ s/"/&quot;/g;
126         if ( ! defined( $value ) || $value eq '')  {
127             $value = $subfieldlib->{defaultvalue};
128             # get today date & replace YYYY, MM, DD if provided in the default value
129             my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
130             $value =~ s/YYYY/$year/g;
131             $value =~ s/MM/$month/g;
132             $value =~ s/DD/$day/g;
133         }
134         
135         $subfield_data{visibility} = "display:none;" if (($subfieldlib->{hidden} > 4) || ($subfieldlib->{hidden} < -4));
136         
137         my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
138         if (!$value && $subfieldlib->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
139             my $CNtag       = substr($pref_itemcallnumber, 0, 3);
140             my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
141             my $CNsubfield2 = substr($pref_itemcallnumber, 4, 1);
142             my $temp2 = $temp->field($CNtag);
143             if ($temp2) {
144                 $value = ($temp2->subfield($CNsubfield)).' '.($temp2->subfield($CNsubfield2));
145                 #remove any trailing space incase one subfield is used
146                 $value =~ s/^\s+|\s+$//g;
147             }
148         }
149         
150         if ($frameworkcode eq 'FA' && $subfieldlib->{kohafield} eq 'items.barcode' && !$value){
151             my $input = new CGI;
152             $value = $input->param('barcode');
153         }
154         my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="$subfield_data{maxlength}" );
155         my $attributes_no_value_textarea = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" rows="5" cols="64" );
156         my $attributes          = qq($attributes_no_value value="$value" );
157         
158         if ( $subfieldlib->{authorised_value} ) {
159             my @authorised_values;
160             my %authorised_lib;
161             # builds list, depending on authorised value...
162             if ( $subfieldlib->{authorised_value} eq "branches" ) {
163                 foreach my $thisbranch (@$branches) {
164                     push @authorised_values, $thisbranch->{value};
165                     $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
166                     $value = $thisbranch->{value} if $thisbranch->{selected} && !$value;
167                 }
168             }
169             elsif ( $subfieldlib->{authorised_value} eq "itemtypes" ) {
170                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
171                   my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description");
172                   $sth->execute;
173                   while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
174                       push @authorised_values, $itemtype;
175                       $authorised_lib{$itemtype} = $description;
176                   }
177         
178                   unless ( $value ) {
179                       my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
180                       $itype_sth->execute( $biblionumber );
181                       ( $value ) = $itype_sth->fetchrow_array;
182                   }
183           
184                   #---- class_sources
185             }
186             elsif ( $subfieldlib->{authorised_value} eq "cn_source" ) {
187                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
188                     
189                   my $class_sources = GetClassSources();
190                   my $default_source = C4::Context->preference("DefaultClassificationSource");
191                   
192                   foreach my $class_source (sort keys %$class_sources) {
193                       next unless $class_sources->{$class_source}->{'used'} or
194                                   ($value and $class_source eq $value)      or
195                                   ($class_source eq $default_source);
196                       push @authorised_values, $class_source;
197                       $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
198                   }
199                           $value = $default_source unless ($value);
200         
201                   #---- "true" authorised value
202             }
203             else {
204                   push @authorised_values, "" unless ( $subfieldlib->{mandatory} );
205                   $authorised_values_sth->execute( $subfieldlib->{authorised_value} );
206                   while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
207                       push @authorised_values, $value;
208                       $authorised_lib{$value} = $lib;
209                   }
210             }
211
212             if ($subfieldlib->{'hidden'}) {
213                 $subfield_data{marc_value} = qq(<input type="hidden" $attributes /> $authorised_lib{$value});
214             }
215             else {
216                 $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
217                     -name     => "field_value",
218                     -values   => \@authorised_values,
219                     -default  => $value,
220                     -labels   => \%authorised_lib,
221                     -override => 1,
222                     -size     => 1,
223                     -multiple => 0,
224                     -tabindex => 1,
225                     -id       => "tag_".$tag."_subfield_".$subfieldtag."_".$index_subfield,
226                     -class    => "input_marceditor",
227                 );
228             }
229
230         }
231             # it's a thesaurus / authority field
232         elsif ( $subfieldlib->{authtypecode} ) {
233                 $subfield_data{marc_value} = "<input type=\"text\" $attributes />
234                     <a href=\"#\" class=\"buttonDot\"
235                         onclick=\"Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=".$subfieldlib->{authtypecode}."&index=$subfield_data{id}','$subfield_data{id}'); return false;\" title=\"Tag Editor\">...</a>
236             ";
237         }
238             # it's a plugin field
239         elsif ( $subfieldlib->{value_builder} ) {
240                 # opening plugin
241                 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $subfieldlib->{'value_builder'};
242                 if (do $plugin) {
243                     my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
244                     my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, $loop_data );
245                     my $change = index($javascript, 'function Change') > -1 ?
246                         "return Change$function_name($subfield_data{random}, '$subfield_data{id}');" :
247                         'return 1;';
248                     $subfield_data{marc_value} = qq[<input $attributes
249                         onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
250                         onchange=" $change"
251                          onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
252                         <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
253                         $javascript];
254                 } else {
255                     warn "Plugin Failed: $plugin";
256                     $subfield_data{marc_value} = "<input $attributes />"; # supply default input form
257                 }
258         }
259         elsif ( $tag eq '' ) {       # it's an hidden field
260             $subfield_data{marc_value} = qq(<input type="hidden" $attributes />);
261         }
262         elsif ( $subfieldlib->{'hidden'} ) {   # FIXME: shouldn't input type be "hidden" ?
263             $subfield_data{marc_value} = qq(<input type="text" $attributes />);
264         }
265         elsif ( length($value) > 100
266                     or (C4::Context->preference("marcflavour") eq "UNIMARC" and
267                           300 <= $tag && $tag < 400 && $subfieldtag eq 'a' )
268                     or (C4::Context->preference("marcflavour") eq "MARC21"  and
269                           500 <= $tag && $tag < 600                     )
270                   ) {
271             # oversize field (textarea)
272             $subfield_data{marc_value} = "<textarea $attributes_no_value_textarea>$value</textarea>\n";
273         } else {
274            # it's a standard field
275            $subfield_data{marc_value} = "<input $attributes />";
276         }
277         
278         return \%subfield_data;
279 }
280
281
282 my $input        = new CGI;
283 my $error        = $input->param('error');
284 my $biblionumber = $input->param('biblionumber');
285 my $itemnumber   = $input->param('itemnumber');
286 my $op           = $input->param('op');
287 my $hostitemnumber = $input->param('hostitemnumber');
288 my $marcflavour  = C4::Context->preference("marcflavour");
289 # fast cataloguing datas
290 my $fa_circborrowernumber = $input->param('circborrowernumber');
291 my $fa_barcode            = $input->param('barcode');
292 my $fa_branch             = $input->param('branch');
293 my $fa_stickyduedate      = $input->param('stickyduedate');
294 my $fa_duedatespec        = $input->param('duedatespec');
295
296 my $frameworkcode = &GetFrameworkCode($biblionumber);
297
298 # Defining which userflag is needing according to the framework currently used
299 my $userflags;
300 if (defined $input->param('frameworkcode')) {
301     $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
302 }
303
304 if (not defined $userflags) {
305     $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
306 }
307
308 my ($template, $loggedinuser, $cookie)
309     = get_template_and_user({template_name => "cataloguing/additem.tt",
310                  query => $input,
311                  type => "intranet",
312                  authnotrequired => 0,
313                  flagsrequired => {editcatalogue => $userflags},
314                  debug => 1,
315                  });
316
317
318 my $today_iso = C4::Dates->today('iso');
319 my $tagslib = &GetMarcStructure(1,$frameworkcode);
320 my $record = GetMarcBiblio($biblionumber);
321 my $oldrecord = TransformMarcToKoha($dbh,$record);
322 my $itemrecord;
323 my $nextop="additem";
324 my @errors; # store errors found while checking data BEFORE saving item.
325 #-------------------------------------------------------------------------------
326 if ($op eq "additem") {
327 #-------------------------------------------------------------------------------
328     # rebuild
329     my @tags      = $input->param('tag');
330     my @subfields = $input->param('subfield');
331     my @values    = $input->param('field_value');
332     # build indicator hash.
333     my @ind_tag   = $input->param('ind_tag');
334     my @indicator = $input->param('indicator');
335     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
336     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
337
338     # type of add
339     my $add_submit                 = $input->param('add_submit');
340     my $add_duplicate_submit       = $input->param('add_duplicate_submit');
341     my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
342     my $number_of_copies           = $input->param('number_of_copies');
343
344     if (C4::Context->preference('autoBarcode') eq 'incremental') {
345         $record = _increment_barcode($record, $frameworkcode);
346     }
347
348     my $addedolditem = TransformMarcToKoha($dbh,$record);
349
350     # If we have to add or add & duplicate, we add the item
351     if ($add_submit || $add_duplicate_submit) {
352         # check for item barcode # being unique
353         my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
354         push @errors,"barcode_not_unique" if($exist_itemnumber);
355         # if barcode exists, don't create, but report The problem.
356     unless ($exist_itemnumber) {
357             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
358         set_item_default_location($oldbibitemnum);
359     }
360         $nextop = "additem";
361         if ($exist_itemnumber) {
362             $itemrecord = $record;
363         }
364     }
365
366     # If we have to add & duplicate
367     if ($add_duplicate_submit) {
368         $itemrecord = $record;
369         if (C4::Context->preference('autoBarcode') eq 'incremental') {
370             $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
371         }
372         else {
373             # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
374             my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
375             my $fieldItem = $itemrecord->field($tagfield);
376             $itemrecord->delete_field($fieldItem);
377             $fieldItem->delete_subfields($tagsubfield);
378             $itemrecord->insert_fields_ordered($fieldItem);
379         }
380     }
381
382     # If we have to add multiple copies
383     if ($add_multiple_copies_submit) {
384
385         use C4::Barcodes;
386         my $barcodeobj = C4::Barcodes->new;
387         my $oldbarcode = $addedolditem->{'barcode'};
388         my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
389
390         # If there is a barcode and we can't find him new values, we can't add multiple copies
391         my $testbarcode;
392         $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
393         if ($oldbarcode && !$testbarcode) {
394
395             push @errors, "no_next_barcode";
396             $itemrecord = $record;
397
398         } else {
399         # We add each item
400
401             # For the first iteration
402             my $barcodevalue = $oldbarcode;
403             my $exist_itemnumber;
404
405
406             for (my $i = 0; $i < $number_of_copies;) {
407
408                 # If there is a barcode
409                 if ($barcodevalue) {
410
411                     # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
412                     $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
413
414                     # Putting it into the record
415                     if ($barcodevalue) {
416                         $record->field($tagfield)->update($tagsubfield => $barcodevalue);
417                     }
418
419                     # Checking if the barcode already exists
420                     $exist_itemnumber = get_item_from_barcode($barcodevalue);
421                 }
422
423                 # Adding the item
424         if (!$exist_itemnumber) {
425             my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
426             set_item_default_location($oldbibitemnum);
427
428             # We count the item only if it was really added
429             # That way, all items are added, even if there was some already existing barcodes
430             # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
431             $i++;
432         }
433
434                 # Preparing the next iteration
435                 $oldbarcode = $barcodevalue;
436             }
437             undef($itemrecord);
438         }
439     }   
440     if ($frameworkcode eq 'FA' && $fa_circborrowernumber){
441         print $input->redirect(
442            '/cgi-bin/koha/circ/circulation.pl?'
443            .'borrowernumber='.$fa_circborrowernumber
444            .'&barcode='.uri_escape($fa_barcode)
445            .'&duedatespec='.$fa_duedatespec
446            .'&stickyduedate=1'
447         );
448         exit;
449     }
450
451
452 #-------------------------------------------------------------------------------
453 } elsif ($op eq "edititem") {
454 #-------------------------------------------------------------------------------
455 # retrieve item if exist => then, it's a modif
456     $itemrecord = C4::Items::GetMarcItem($biblionumber,$itemnumber);
457     $nextop = "saveitem";
458 #-------------------------------------------------------------------------------
459 } elsif ($op eq "delitem") {
460 #-------------------------------------------------------------------------------
461     # check that there is no issue on this item before deletion.
462     $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
463     if($error == 1){
464         print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
465     }else{
466         push @errors,$error;
467         $nextop="additem";
468     }
469 #-------------------------------------------------------------------------------
470 } elsif ($op eq "delallitems") {
471 #-------------------------------------------------------------------------------
472     my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
473     my $errortest=0;
474     my $itemfail;
475     foreach my $biblioitem (@biblioitems) {
476         my $items = &GetItemsByBiblioitemnumber( $biblioitem->{biblioitemnumber} );
477
478         foreach my $item (@$items) {
479             $error =&DelItemCheck( $dbh, $biblionumber, $item->{itemnumber} );
480             $itemfail =$item;
481         if($error == 1){
482             next
483             }
484         else {
485             push @errors,$error;
486             $errortest++
487             }
488         }
489         if($errortest > 0){
490             $nextop="additem";
491         } 
492         else {
493             my $defaultview = C4::Context->preference('IntranetBiblioDefaultView');
494             my $views = { C4::Search::enabled_staff_search_views };
495             if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) {
496                 print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber");
497             } elsif  ($defaultview eq 'marc' && $views->{can_view_MARC}) {
498                 print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber");
499             } elsif  ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) {
500                 print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber");
501             } else {
502                 print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber");
503             }
504             exit;
505         }
506         }
507 #-------------------------------------------------------------------------------
508 } elsif ($op eq "saveitem") {
509 #-------------------------------------------------------------------------------
510     # rebuild
511     my @tags      = $input->param('tag');
512     my @subfields = $input->param('subfield');
513     my @values    = $input->param('field_value');
514     # build indicator hash.
515     my @ind_tag   = $input->param('ind_tag');
516     my @indicator = $input->param('indicator');
517     # my $itemnumber = $input->param('itemnumber');
518     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag,'ITEM');
519     my $itemtosave=MARC::Record::new_from_xml($xml, 'UTF-8');
520     # MARC::Record builded => now, record in DB
521     # warn "R: ".$record->as_formatted;
522     # check that the barcode don't exist already
523     my $addedolditem = TransformMarcToKoha($dbh,$itemtosave);
524     my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
525     if ($exist_itemnumber && $exist_itemnumber != $itemnumber) {
526         push @errors,"barcode_not_unique";
527     } else {
528         ModItemFromMarc($itemtosave,$biblionumber,$itemnumber);
529         $itemnumber="";
530     }
531     $nextop="additem";
532 } elsif ($op eq "delinkitem"){
533     my $analyticfield = '773';
534         if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC'){
535         $analyticfield = '773';
536     } elsif ($marcflavour eq 'UNIMARC') {
537         $analyticfield = '461';
538     }
539     foreach my $field ($record->field($analyticfield)){
540         if ($field->subfield('9') eq $hostitemnumber){
541             $record->delete_field($field);
542             last;
543         }
544     }
545         my $modbibresult = ModBiblio($record, $biblionumber,'');
546 }
547
548 #
549 #-------------------------------------------------------------------------------
550 # build screen with existing items. and "new" one
551 #-------------------------------------------------------------------------------
552
553 # now, build existiing item list
554 my $temp = GetMarcBiblio( $biblionumber );
555 #my @fields = $record->fields();
556
557
558 my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
559 my @big_array;
560 #---- finds where items.itemnumber is stored
561 my (  $itemtagfield,   $itemtagsubfield) = &GetMarcFromKohaField("items.itemnumber", $frameworkcode);
562 my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebranch", $frameworkcode);
563 C4::Biblio::EmbedItemsInMarcBiblio($temp, $biblionumber);
564 my @fields = $temp->fields();
565
566
567 my @hostitemnumbers;
568 if ( C4::Context->preference('EasyAnalyticalRecords') ) {
569     my $analyticfield = '773';
570     if ($marcflavour  eq 'MARC21' || $marcflavour eq 'NORMARC') {
571         $analyticfield = '773';
572     } elsif ($marcflavour eq 'UNIMARC') {
573         $analyticfield = '461';
574     }
575     foreach my $hostfield ($temp->field($analyticfield)){
576         my $hostbiblionumber = $hostfield->subfield('0');
577         if ($hostbiblionumber){
578             my $hostrecord = GetMarcBiblio($hostbiblionumber, 1);
579             if ($hostrecord) {
580                 my ($itemfield, undef) = GetMarcFromKohaField( 'items.itemnumber', GetFrameworkCode($hostbiblionumber) );
581                 foreach my $hostitem ($hostrecord->field($itemfield)){
582                     if ($hostitem->subfield('9') eq $hostfield->subfield('9')){
583                         push (@fields, $hostitem);
584                         push (@hostitemnumbers, $hostfield->subfield('9'));
585                     }
586                 }
587             }
588         }
589     }
590 }
591
592
593 foreach my $field (@fields) {
594     next if ( $field->tag() < 10 );
595
596     my @subf = $field->subfields or ();    # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
597     my %this_row;
598     # loop through each subfield
599     my $i = 0;
600     foreach my $subfield (@subf){
601         my $subfieldcode = $subfield->[0];
602         my $subfieldvalue= $subfield->[1];
603
604         next if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab} ne 10 
605                 && ($field->tag() ne $itemtagfield 
606                 && $subfieldcode   ne $itemtagsubfield));
607         $witness{$subfieldcode} = $tagslib->{$field->tag()}->{$subfieldcode}->{lib} if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10);
608                 if ($tagslib->{$field->tag()}->{$subfieldcode}->{tab}  eq 10) {
609                     $this_row{$subfieldcode} .= " | " if($this_row{$subfieldcode});
610                 $this_row{$subfieldcode} .= GetAuthorisedValueDesc( $field->tag(),
611                         $subfieldcode, $subfieldvalue, '', $tagslib) 
612                                                 || $subfieldvalue;
613         }
614
615         if (($field->tag eq $branchtagfield) && ($subfieldcode eq $branchtagsubfield) && C4::Context->preference("IndependantBranches")) {
616             #verifying rights
617             my $userenv = C4::Context->userenv();
618             unless (($userenv->{'flags'} == 1) or (($userenv->{'branch'} eq $subfieldvalue))){
619                 $this_row{'nomod'} = 1;
620             }
621         }
622         $this_row{itemnumber} = $subfieldvalue if ($field->tag() eq $itemtagfield && $subfieldcode eq $itemtagsubfield);
623
624         if ( C4::Context->preference('EasyAnalyticalRecords') ) {
625             foreach my $hostitemnumber (@hostitemnumbers){
626                 if ($this_row{itemnumber} eq $hostitemnumber){
627                         $this_row{hostitemflag} = 1;
628                         $this_row{hostbiblionumber}= GetBiblionumberFromItemnumber($hostitemnumber);
629                         last;
630                 }
631             }
632
633 #           my $countanalytics=GetAnalyticsCount($this_row{itemnumber});
634 #           if ($countanalytics > 0){
635 #                $this_row{countanalytics} = $countanalytics;
636 #           }
637         }
638
639     }
640     if (%this_row) {
641         push(@big_array, \%this_row);
642     }
643 }
644
645 my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField("items.holdingbranch",$frameworkcode);
646 @big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
647
648 # now, construct template !
649 # First, the existing items for display
650 my @item_value_loop;
651 my @header_value_loop;
652 for my $row ( @big_array ) {
653     my %row_data;
654     my @item_fields = map +{ field => $_ || '' }, @$row{ sort keys(%witness) };
655     $row_data{item_value} = [ @item_fields ];
656     $row_data{itemnumber} = $row->{itemnumber};
657     #reporting this_row values
658     $row_data{'nomod'} = $row->{'nomod'};
659     $row_data{'hostitemflag'} = $row->{'hostitemflag'};
660     $row_data{'hostbiblionumber'} = $row->{'hostbiblionumber'};
661 #       $row_data{'countanalytics'} = $row->{'countanalytics'};
662     push(@item_value_loop,\%row_data);
663 }
664 foreach my $subfield_code (sort keys(%witness)) {
665     my %header_value;
666     $header_value{header_value} = $witness{$subfield_code};
667     push(@header_value_loop, \%header_value);
668 }
669
670 # now, build the item form for entering a new item
671 my @loop_data =();
672 my $i=0;
673
674 my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
675
676 my $onlymine = C4::Context->preference('IndependantBranches') && 
677                C4::Context->userenv                           && 
678                C4::Context->userenv->{flags}!=1               && 
679                C4::Context->userenv->{branch};
680 my $branch = $input->param('branch') || C4::Context->userenv->{branch};
681 my $branches = GetBranchesLoop($branch,$onlymine);  # build once ahead of time, instead of multiple times later.
682
683 # We generate form, from actuel record
684 @fields = ();
685 if($itemrecord){
686     foreach my $field ($itemrecord->fields()){
687         my $tag = $field->{_tag};
688         foreach my $subfield ( $field->subfields() ){
689
690             my $subfieldtag = $subfield->[0];
691             my $value       = $subfield->[1];
692             my $subfieldlib = $tagslib->{$tag}->{$subfieldtag};
693
694             next if subfield_is_koha_internal_p($subfieldtag);
695             next if ($tagslib->{$tag}->{$subfieldtag}->{'tab'} ne "10");
696
697             my $subfield_data = generate_subfield_form($tag, $subfieldtag, $value, $tagslib, $subfieldlib, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i);        
698
699             push @fields, "$tag$subfieldtag";
700             push (@loop_data, $subfield_data);
701             $i++;
702                     }
703
704                 }
705             }
706     # and now we add fields that are empty
707
708 foreach my $tag ( keys %{$tagslib}){
709     foreach my $subtag (keys %{$tagslib->{$tag}}){
710         next if subfield_is_koha_internal_p($subtag);
711         next if ($tagslib->{$tag}->{$subtag}->{'tab'} ne "10");
712         next if any { /^$tag$subtag$/ }  @fields;
713
714         my @values = (undef);
715         @values = $itemrecord->field($tag)->subfield($subtag) if ($itemrecord && defined($itemrecord->field($tag)->subfield($subtag)));
716         for my $value (@values){
717             my $subfield_data = generate_subfield_form($tag, $subtag, $value, $tagslib, $tagslib->{$tag}->{$subtag}, $branches, $today_iso, $biblionumber, $temp, \@loop_data, $i); 
718             push (@loop_data, $subfield_data);
719             $i++;
720         } 
721   }
722 }
723 @loop_data = sort {$a->{subfield} cmp $b->{subfield} } @loop_data;
724
725 # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit.
726 $template->param( title => $record->title() ) if ($record ne "-1");
727 $template->param(
728     biblionumber => $biblionumber,
729     title        => $oldrecord->{title},
730     author       => $oldrecord->{author},
731     item_loop        => \@item_value_loop,
732     item_header_loop => \@header_value_loop,
733     item             => \@loop_data,
734     itemnumber       => $itemnumber,
735     itemtagfield     => $itemtagfield,
736     itemtagsubfield  => $itemtagsubfield,
737     op      => $nextop,
738     opisadd => ($nextop eq "saveitem") ? 0 : 1,
739     C4::Search::enabled_staff_search_views,
740 );
741
742 if ($frameworkcode eq 'FA'){
743     # fast cataloguing datas
744     $template->param(
745         'circborrowernumber' => $fa_circborrowernumber,
746         'barcode'            => $fa_barcode,
747         'branch'             => $fa_branch,
748         'stickyduedate'      => $fa_stickyduedate,
749         'duedatespec'        => $fa_duedatespec,
750     );
751 }
752
753 foreach my $error (@errors) {
754     $template->param($error => 1);
755 }
756 output_html_with_http_headers $input, $cookie, $template->output;