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