Merge remote branch 'kc/new/enh/bug_1962' into kcmaster
[koha.git] / acqui / neworderempty.pl
1 #!/usr/bin/perl
2
3 #script to show display basket of orders
4 #written by chris@katipo.co.nz 24/2/2000
5
6 # Copyright 2000-2002 Katipo Communications
7 #
8 # This file is part of Koha.
9 #
10 # Koha is free software; you can redistribute it and/or modify it under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
13 # version.
14 #
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License along
20 # with Koha; if not, write to the Free Software Foundation, Inc.,
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22
23
24 =head1 NAME
25
26 neworderempty.pl
27
28 =head1 DESCRIPTION
29
30 this script allows to create a new record to order it. This record shouldn't exist
31 on database.
32
33 =head1 CGI PARAMETERS
34
35 =over 4
36
37 =item booksellerid
38 the bookseller the librarian has to buy a new book.
39
40 =item title
41 the title of this new record.
42
43 =item author
44 the author of this new record.
45
46 =item publication year
47 the publication year of this new record.
48
49 =item ordernumber
50 the number of this order.
51
52 =item biblio
53
54 =item basketno
55 the basket number for this new order.
56
57 =item suggestionid
58 if this order comes from a suggestion.
59
60 =item breedingid
61 the item's id in the breeding reservoir
62
63 =item close
64
65 =back
66
67 =cut
68
69 use warnings;
70 use strict;
71 use CGI;
72 use C4::Context;
73 use C4::Input;
74
75 use C4::Auth;
76 use C4::Budgets;
77 use C4::Input;
78 use C4::Dates;
79
80 use C4::Bookseller  qw/ GetBookSellerFromId /;
81 use C4::Acquisition;
82 use C4::Suggestions;    # GetSuggestion
83 use C4::Biblio;                 # GetBiblioData
84 use C4::Output;
85 use C4::Input;
86 use C4::Koha;
87 use C4::Branch;                 # GetBranches
88 use C4::Members;
89 use C4::Search qw/FindDuplicate BiblioAddAuthorities/;
90
91 #needed for z3950 import:
92 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
93
94 my $input           = new CGI;
95 my $booksellerid    = $input->param('booksellerid');    # FIXME: else ERROR!
96 my $budget_id       = $input->param('budget_id') || 0;  # FIXME: else ERROR!
97 my $title           = $input->param('title');
98 my $author          = $input->param('author');
99 my $publicationyear = $input->param('publicationyear');
100 my $bookseller      = GetBookSellerFromId($booksellerid);       # FIXME: else ERROR!
101 my $ordernumber          = $input->param('ordernumber') || '';
102 my $biblionumber    = $input->param('biblionumber');
103 my $basketno        = $input->param('basketno');
104 my $suggestionid    = $input->param('suggestionid');
105 my $close           = $input->param('close');
106 my $uncertainprice  = $input->param('uncertainprice');
107 my $import_batch_id = $input->param('import_batch_id'); # if this is filled, we come from a staged file, and we will return here after saving the order !
108 my $data;
109 my $new = 'no';
110
111 my $budget_name;
112
113 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
114     {
115         template_name   => "acqui/neworderempty.tmpl",
116         query           => $input,
117         type            => "intranet",
118         authnotrequired => 0,
119         flagsrequired   => { acquisition => 'order_manage' },
120         debug           => 1,
121     }
122 );
123
124 my $basket = GetBasket($basketno);
125 my $contract = &GetContract($basket->{contractnumber});
126
127 #simple parameters reading (all in one :-)
128 my $params = $input->Vars;
129 my $listprice=0; # the price, that can be in MARC record if we have one
130 if ( $ordernumber eq '' and defined $params->{'breedingid'}){
131 #we want to import from the breeding reservoir (from a z3950 search)
132     my ($marcrecord, $encoding) = MARCfindbreeding($params->{'breedingid'});
133     die("Could not find the selected record in the reservoir, bailing") unless $marcrecord;
134
135     my $duplicatetitle;
136 #look for duplicates
137     ($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord);
138     if($biblionumber && !$input->param('use_external_source')) {
139         #if duplicate record found and user did not decide yet, first warn user
140         #and let him choose between using new record or existing record
141         Load_Duplicate($duplicatetitle);
142         exit;
143     }
144     #from this point: add a new record
145         if (C4::Context->preference("BiblioAddsAuthorities")){
146             my ($countlinked,$countcreated)=BiblioAddAuthorities($marcrecord, $params->{'frameworkcode'});
147         }
148         my $bibitemnum;
149         $params->{'frameworkcode'} or $params->{'frameworkcode'} = "";
150         ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $params->{'frameworkcode'} );
151         # get the price if there is one.
152         # filter by storing only the 1st number
153         # we suppose the currency is correct, as we have no possibilities to get it.
154         if ($marcrecord->subfield("345","d")) {
155             $listprice = $marcrecord->subfield("345","d");
156             if ($listprice =~ /^([\d\.,]*)/) {
157                 $listprice = $1;
158                 $listprice =~ s/,/\./;
159             } else {
160                 $listprice = 0;
161             }
162         }
163         elsif ($marcrecord->subfield("010","d")) {
164             $listprice = $marcrecord->subfield("010","d");
165             if ($listprice =~ /^([\d\.,]*)/) {
166                 $listprice = $1;
167                 $listprice =~ s/,/\./;
168             } else {
169                 $listprice = 0;
170             }
171         }
172         SetImportRecordStatus($params->{'breedingid'}, 'imported');
173 }
174
175
176
177 if ( $ordernumber eq '' ) {    # create order
178     $new = 'yes';
179
180     #   $ordernumber=newordernum;
181     if ( $biblionumber && !$suggestionid ) {
182         $data = GetBiblioData($biblionumber);
183     }
184
185 # get suggestion fields if applicable. If it's a subscription renewal, then the biblio already exists
186 # otherwise, retrieve suggestion information.
187     if ($suggestionid) {
188         $data = ($biblionumber) ? GetBiblioData($biblionumber) : GetSuggestion($suggestionid);
189     }
190 }
191 else {    #modify order
192     $data   = GetOrder($ordernumber);
193     $biblionumber = $data->{'biblionumber'};
194     $budget_id = $data->{'budget_id'};
195
196     #get basketno and supplierno. too!
197     my $data2 = GetBasket( $data->{'basketno'} );
198     $basketno     = $data2->{'basketno'};
199     $booksellerid = $data2->{'booksellerid'};
200 }
201
202 # get currencies (for change rates calcs if needed)
203 my $active_currency = GetCurrency();
204 my $default_currency;
205 if (! $data->{currency} ) { # New order no currency set
206     if ( $bookseller->{listprice} ) {
207         $default_currency = $bookseller->{listprice};
208     }
209     else {
210         $default_currency = $active_currency->{currency};
211     }
212 }
213
214 my @rates = GetCurrencies();
215
216 # ## @rates
217
218 my @loop_currency = ();
219 for my $curr ( @rates ) {
220     my $selected;
221     if ($data->{currency} ) {
222         $selected = $curr->{currency} eq $data->{currency};
223     }
224     else {
225         $selected = $curr->{currency} eq $default_currency;
226     }
227     push @loop_currency, {
228         currcode => $curr->{currency},
229         rate     => $curr->{rate},
230         selected => $selected,
231     }
232 }
233
234 # build branches list
235 my $onlymine=C4::Context->preference('IndependantBranches') && 
236             C4::Context->userenv && 
237             C4::Context->userenv->{flags}!=1 && 
238             C4::Context->userenv->{branch};
239 my $branches = GetBranches($onlymine);
240 my @branchloop;
241 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
242     my %row = (
243         value      => $thisbranch,
244         branchname => $branches->{$thisbranch}->{'branchname'},
245     );
246     $row{'selected'} = 1 if( $thisbranch eq $data->{branchcode}) ;
247     push @branchloop, \%row;
248 }
249 $template->param( branchloop => \@branchloop );
250
251 # build bookfund list
252 my $borrower= GetMember('borrowernumber' => $loggedinuser);
253 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
254
255 my $budget =  GetBudget($budget_id);
256 # build budget list
257 my $budget_loop = [];
258 my $budgets = GetBudgetHierarchy(q{},$borrower->{branchcode},$borrower->{borrowernumber});
259 foreach my $r (@{$budgets}) {
260     if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
261         next;
262     }
263     push @{$budget_loop}, {
264         b_id  => $r->{budget_id},
265         b_txt => $r->{budget_name},
266         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
267     };
268 }
269
270
271 if ($close) {
272     $budget_id      =  $data->{'budget_id'};
273     $budget_name    =   $budget->{'budget_name'};
274
275 }
276
277 my $CGIsort1;
278 if ($budget) {    # its a mod ..
279     if ( defined $budget->{'sort1_authcat'} ) {    # with custom  Asort* planning values
280         $CGIsort1 = GetAuthvalueDropbox( 'sort1', $budget->{'sort1_authcat'}, $data->{'sort1'} );
281     }
282 } elsif(scalar(@$budgets)){
283     $CGIsort1 = GetAuthvalueDropbox( 'sort1', @$budgets[0]->{'sort1_authcat'}, '' );
284 }else{
285     $CGIsort1 = GetAuthvalueDropbox( 'sort1','', '' );
286 }
287
288 # if CGIsort is successfully fetched, the use it
289 # else - failback to plain input-field
290 if ($CGIsort1) {
291     $template->param( CGIsort1 => $CGIsort1 );
292 } else {
293     $template->param( sort1 => $data->{'sort1'} );
294 }
295
296 my $CGIsort2;
297 if ($budget) {
298     if ( defined $budget->{'sort2_authcat'} ) {
299         $CGIsort2 = GetAuthvalueDropbox( 'sort2', $budget->{'sort2_authcat'}, $data->{'sort2'} );
300     }
301 } elsif(scalar(@$budgets)) {
302     $CGIsort2 = GetAuthvalueDropbox( 'sort2', @$budgets[0]->{sort2_authcat}, '' );
303 }else{
304     $CGIsort2 = GetAuthvalueDropbox( 'sort2','', '' );
305 }
306
307 if ($CGIsort2) {
308     $template->param( CGIsort2 => $CGIsort2 );
309 } else {
310     $template->param( sort2 => $data->{'sort2'} );
311 }
312
313 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
314     # prepare empty item form
315     my $cell = PrepareItemrecordDisplay('','','','ACQ');
316 #     warn "==> ".Data::Dumper::Dumper($cell);
317     unless ($cell) {
318         $cell = PrepareItemrecordDisplay('','','','');
319         $template->param('NoACQframework' => 1);
320     }
321     my @itemloop;
322     push @itemloop,$cell;
323     
324     $template->param(items => \@itemloop);
325 }
326
327 # fill template
328 $template->param(
329     close        => $close,
330     budget_id    => $budget_id,
331     budget_name  => $budget_name
332 ) if ($close);
333
334 $template->param(
335     existing         => $biblionumber,
336     ordernumber           => $ordernumber,
337     # basket informations
338     basketno             => $basketno,
339     basketname           => $basket->{'basketname'},
340     basketnote           => $basket->{'note'},
341     booksellerid         => $basket->{'booksellerid'},
342     basketbooksellernote => $basket->{booksellernote},
343     basketcontractno     => $basket->{contractnumber},
344     basketcontractname   => $contract->{contractname},
345     creationdate         => C4::Dates->new($basket->{creationdate},'iso')->output,
346     authorisedby         => $basket->{'authorisedby'},
347     authorisedbyname     => $basket->{'authorisedbyname'},
348     closedate            => C4::Dates->new($basket->{'closedate'},'iso')->output,
349     # order details
350     suggestionid     => $suggestionid,
351     biblionumber     => $biblionumber,
352     uncertainprice   => $data->{'uncertainprice'},
353     authorisedbyname => $borrower->{'firstname'} . " " . $borrower->{'surname'},
354     biblioitemnumber => $data->{'biblioitemnumber'},
355     discount_2dp     => sprintf( "%.2f",  $bookseller->{'discount'}) ,   # for display
356     discount         => $bookseller->{'discount'},
357     listincgst       => $bookseller->{'listincgst'},
358     invoiceincgst    => $bookseller->{'invoiceincgst'},
359     name             => $bookseller->{'name'},
360     cur_active_sym   => $active_currency->{'symbol'},
361     cur_active       => $active_currency->{'currency'},
362     loop_currencies  => \@loop_currency,
363     orderexists      => ( $new eq 'yes' ) ? 0 : 1,
364     title            => $data->{'title'},
365     author           => $data->{'author'},
366     publicationyear  => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
367     budget_loop      => $budget_loop,
368     isbn             => $data->{'isbn'},
369     seriestitle      => $data->{'seriestitle'},
370     quantity         => $data->{'quantity'},
371     quantityrec      => $data->{'quantity'},
372     rrp              => $data->{'rrp'},
373     listprice        => sprintf("%.2f", $data->{'listprice'}||$data->{'price'}||$listprice),
374     total            => sprintf("%.2f", ($data->{'ecost'}||0)*($data->{'quantity'}||0) ),
375     ecost            => $data->{'ecost'},
376     notes            => $data->{'notes'},
377     publishercode    => $data->{'publishercode'},
378     
379     import_batch_id  => $import_batch_id,
380
381 # CHECKME: gst-stuff needs verifing, mason.
382     gstrate          => $bookseller->{'gstrate'} // C4::Context->preference("gist") // 0,
383     gstreg           => $bookseller->{'gstreg'},
384 );
385
386 output_html_with_http_headers $input, $cookie, $template->output;
387
388
389 =head2 MARCfindbreeding
390
391   $record = MARCfindbreeding($breedingid);
392
393 Look up the import record repository for the record with
394 record with id $breedingid.  If found, returns the decoded
395 MARC::Record; otherwise, -1 is returned (FIXME).
396 Returns as second parameter the character encoding.
397
398 =cut
399
400 sub MARCfindbreeding {
401     my ( $id ) = @_;
402     my ($marc, $encoding) = GetImportRecordMarc($id);
403     # remove the - in isbn, koha store isbn without any -
404     if ($marc) {
405         my $record = MARC::Record->new_from_usmarc($marc);
406         my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
407         if ( $record->field($isbnfield) ) {
408             foreach my $field ( $record->field($isbnfield) ) {
409                 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
410                     my $newisbn = $field->subfield($isbnsubfield);
411                     $newisbn =~ s/-//g;
412                     $field->update( $isbnsubfield => $newisbn );
413                 }
414             }
415         }
416         # fix the unimarc 100 coded field (with unicode information)
417         if (C4::Context->preference('marcflavour') eq 'UNIMARC' && $record->subfield(100,'a')) {
418             my $f100a=$record->subfield(100,'a');
419             my $f100 = $record->field(100);
420             my $f100temp = $f100->as_string;
421             $record->delete_field($f100);
422             if ( length($f100temp) > 28 ) {
423                 substr( $f100temp, 26, 2, "50" );
424                 $f100->update( 'a' => $f100temp );
425                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
426                 $record->insert_fields_ordered($f100);
427             }
428         }
429         
430         if ( !defined(ref($record)) ) {
431             return -1;
432         }
433         else {
434             # normalize author : probably UNIMARC specific...
435             if (    C4::Context->preference("z3950NormalizeAuthor")
436                 and C4::Context->preference("z3950AuthorAuthFields") )
437             {
438                 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author");
439
440 #                 my $summary = C4::Context->preference("z3950authortemplate");
441                 my $auth_fields =
442                 C4::Context->preference("z3950AuthorAuthFields");
443                 my @auth_fields = split /,/, $auth_fields;
444                 my $field;
445
446                 if ( $record->field($tag) ) {
447                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
448
449     #                        foreach my $subfieldcode ($tmpfield->subfields){
450                         my $subfieldcode  = shift @$tmpfield;
451                         my $subfieldvalue = shift @$tmpfield;
452                         if ($field) {
453                             $field->add_subfields(
454                                 "$subfieldcode" => $subfieldvalue )
455                             if ( $subfieldcode ne $subfield );
456                         }
457                         else {
458                             $field =
459                             MARC::Field->new( $tag, "", "",
460                                 $subfieldcode => $subfieldvalue )
461                             if ( $subfieldcode ne $subfield );
462                         }
463                     }
464                 }
465                 $record->delete_field( $record->field($tag) );
466                 foreach my $fieldtag (@auth_fields) {
467                     next unless ( $record->field($fieldtag) );
468                     my $lastname  = $record->field($fieldtag)->subfield('a');
469                     my $firstname = $record->field($fieldtag)->subfield('b');
470                     my $title     = $record->field($fieldtag)->subfield('c');
471                     my $number    = $record->field($fieldtag)->subfield('d');
472                     if ($title) {
473
474 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
475                         $field->add_subfields(
476                                 "$subfield" => ucfirst($title) . " "
477                             . ucfirst($firstname) . " "
478                             . $number );
479                     }
480                     else {
481
482 #                       $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
483                         $field->add_subfields(
484                             "$subfield" => ucfirst($firstname) . ", "
485                             . ucfirst($lastname) );
486                     }
487                 }
488                 $record->insert_fields_ordered($field);
489             }
490             return $record, $encoding;
491         }
492     }
493     return -1;
494 }
495
496 sub Load_Duplicate {
497   my ($duplicatetitle)= @_;
498   ($template, $loggedinuser, $cookie) = get_template_and_user(
499     {
500         template_name   => "acqui/neworderempty_duplicate.tmpl",
501         query           => $input,
502         type            => "intranet",
503         authnotrequired => 0,
504         flagsrequired   => { acquisition => 'order_manage' },
505 #        debug           => 1,
506     }
507   );
508
509   $template->param(
510     biblionumber        => $biblionumber,
511     basketno            => $basketno,
512     booksellerid        => $basket->{'booksellerid'},
513     breedingid          => $params->{'breedingid'},
514     duplicatetitle      => $duplicatetitle,
515   );
516
517   output_html_with_http_headers $input, $cookie, $template->output;
518 }