Bug 20623: Fix basket group PDF when itemtype not itemtype table
[koha.git] / acqui / basketgroup.pl
1 #!/usr/bin/perl
2
3 #script to group (closed) baskets into basket groups for easier order management
4 #written by john.soros@biblibre.com 01/10/2008
5
6 # Copyright 2008 - 2009 BibLibre SARL
7 # Parts Copyright Catalyst 2010
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23
24
25 =head1 NAME
26
27 basketgroup.pl
28
29 =head1 DESCRIPTION
30
31  This script lets the user group (closed) baskets into basket groups for easier order management. Note that the grouped baskets have to be from the same bookseller and
32  have to be closed to be printed or exported.
33
34 =head1 CGI PARAMETERS
35
36 =over 4
37
38 =item $booksellerid
39
40 The bookseller who we want to display the baskets (and basketgroups) of.
41
42 =back
43
44 =cut
45
46 use Modern::Perl;
47 use Carp;
48
49 use C4::Auth;
50 use C4::Output;
51 use CGI qw ( -utf8 );
52
53 use C4::Acquisition qw/CloseBasketgroup ReOpenBasketgroup GetOrders GetBasketsByBasketgroup GetBasketsByBookseller ModBasketgroup NewBasketgroup DelBasketgroup GetBasketgroups ModBasket GetBasketgroup GetBasket GetBasketGroupAsCSV/;
54 use Koha::EDI qw/create_edi_order get_edifact_ean/;
55
56 use Koha::Biblioitems;
57 use Koha::Acquisition::Booksellers;
58 use Koha::ItemTypes;
59 use Koha::Patrons;
60
61 our $input=new CGI;
62
63 our ($template, $loggedinuser, $cookie)
64     = get_template_and_user({template_name => "acqui/basketgroup.tt",
65                              query => $input,
66                              type => "intranet",
67                              authnotrequired => 0,
68                              flagsrequired => {acquisition => 'group_manage'},
69                              debug => 1,
70                 });
71
72 sub BasketTotal {
73     my $basketno = shift;
74     my $bookseller = shift;
75     my $total = 0;
76     my @orders = GetOrders($basketno);
77     for my $order (@orders){
78         # FIXME The following is wrong
79         if ( $bookseller->listincgst ) {
80             $total = $total + ( $order->{ecost_tax_included} * $order->{quantity} );
81         } else {
82             $total = $total + ( $order->{ecost_tax_excluded} * $order->{quantity} );
83         }
84     }
85     return $total;
86 }
87
88 #displays all basketgroups and all closed baskets (in their respective groups)
89 sub displaybasketgroups {
90     my $basketgroups = shift;
91     my $bookseller = shift;
92     my $baskets = shift;
93     if (scalar @$basketgroups != 0) {
94         foreach my $basketgroup (@$basketgroups){
95             my $i = 0;
96             my $basketsqty = 0;
97             while($i < scalar(@$baskets)){
98                 my $basket = @$baskets[$i];
99                 if($basket->{'basketgroupid'} && $basket->{'basketgroupid'} == $basketgroup->{'id'}){
100                     $basket->{total} = BasketTotal($basket->{basketno}, $bookseller);
101                     push(@{$basketgroup->{'baskets'}}, $basket);
102                     splice(@$baskets, $i, 1);
103                     ++$basketsqty;
104                     --$i;
105                 }
106                 ++$i;
107             }
108             $basketgroup -> {'basketsqty'} = $basketsqty;
109         }
110         $template->param(basketgroups => $basketgroups);
111     }
112     for(my $i=0; $i < scalar @$baskets; ++$i) {
113         if( ! @$baskets[$i]->{'closedate'} ) {
114             splice(@$baskets, $i, 1);
115             --$i;
116         }else{
117             @$baskets[$i]->{total} = BasketTotal(@$baskets[$i]->{basketno}, $bookseller);
118         }
119     }
120     $template->param(baskets => $baskets);
121     $template->param( booksellername => $bookseller->name);
122 }
123
124 sub printbasketgrouppdf{
125     my ($basketgroupid) = @_;
126     
127     my $pdfformat = C4::Context->preference("OrderPdfFormat");
128     if ($pdfformat eq 'pdfformat::layout3pages' || $pdfformat eq 'pdfformat::layout2pages' || $pdfformat eq 'pdfformat::layout3pagesfr'
129         || $pdfformat eq 'pdfformat::layout2pagesde'){
130         eval {
131         eval "require $pdfformat";
132             import $pdfformat;
133         };
134         if ($@){
135         }
136     }
137     else {
138         print $input->header;  
139         print $input->start_html;  # FIXME Should do a nicer page
140         print "<h1>Invalid PDF Format set</h1>";
141         print "Please go to the systempreferences and set a valid pdfformat";
142         exit;
143     }
144     
145     my $basketgroup = GetBasketgroup($basketgroupid);
146     my $bookseller = Koha::Acquisition::Booksellers->find( $basketgroup->{booksellerid} );
147     my $baskets = GetBasketsByBasketgroup($basketgroupid);
148     
149     my %orders;
150     for my $basket (@$baskets) {
151         my @ba_orders;
152         my @ords = &GetOrders($basket->{basketno});
153         for my $ord (@ords) {
154
155             next unless ( $ord->{biblionumber} or $ord->{quantity}> 0 );
156             eval {
157                 require C4::Biblio;
158                 import C4::Biblio;
159             };
160             if ($@){
161                 croak $@;
162             }
163             eval {
164                 require C4::Koha;
165                 import C4::Koha;
166             };
167             if ($@){
168                 croak $@;
169             }
170
171             $ord->{tax_value} = $ord->{tax_value_on_ordering};
172             $ord->{tax_rate} = $ord->{tax_rate_on_ordering};
173             $ord->{total_tax_included} = $ord->{ecost_tax_included} * $ord->{quantity};
174             $ord->{total_tax_excluded} = $ord->{ecost_tax_excluded} * $ord->{quantity};
175
176             my $biblioitem = Koha::Biblioitems->search({ biblionumber => $ord->{biblionumber} })->next;
177
178             #FIXME DELETE ME
179             # 0      1        2        3         4            5         6       7      8        9
180             #isbn, itemtype, author, title, publishercode, quantity, listprice ecost discount tax_rate
181
182             # Editor Number
183             my $en;
184             my $edition;
185             $ord->{marcxml} = C4::Biblio::GetXmlBiblio( $ord->{biblionumber} );
186             my $marcrecord=eval{MARC::Record::new_from_xml( $ord->{marcxml},'UTF-8' )};
187             if ($marcrecord){
188                 if ( C4::Context->preference("marcflavour") eq 'UNIMARC' ) {
189                     $en = $marcrecord->subfield( '345', "b" );
190                     $edition = $marcrecord->subfield( '205', 'a' );
191                 } elsif ( C4::Context->preference("marcflavour") eq 'MARC21' ) {
192                     $en = $marcrecord->subfield( '037', "a" );
193                     $edition = $marcrecord->subfield( '250', 'a' );
194                 }
195             }
196
197             my $item_has_type_description = ($ord->{itemtype}
198                                          and $biblioitem->itemtype
199                                          and Koha::ItemTypes->find( $biblioitem->itemtype ));
200             $ord->{itemtype} = $item_has_type_description ? Koha::ItemTypes->find( $biblioitem->itemtype )->description : undef;
201             $ord->{en} = $en ? $en : undef;
202             $ord->{edition} = $edition ? $edition : undef;
203
204             push(@ba_orders, $ord);
205         }
206         $orders{$basket->{basketno}} = \@ba_orders;
207     }
208     print $input->header(
209         -type       => 'application/pdf',
210         -attachment => ( $basketgroup->{name} || $basketgroupid ) . '.pdf'
211     );
212     my $pdf = printpdf($basketgroup, $bookseller, $baskets, \%orders, $bookseller->tax_rate // C4::Context->preference("gist")) || die "pdf generation failed";
213     print $pdf;
214
215 }
216
217 sub generate_edifact_orders {
218     my $basketgroupid = shift;
219     my $baskets       = GetBasketsByBasketgroup($basketgroupid);
220     my $ean           = get_edifact_ean();
221
222     for my $basket ( @{$baskets} ) {
223         create_edi_order( { ean => $ean, basketno => $basket->{basketno}, } );
224     }
225     return;
226 }
227
228 my $op = $input->param('op') || 'display';
229 # possible values of $op :
230 # - add : adds a new basketgroup, or edit an open basketgroup, or display a closed basketgroup
231 # - mod_basket : modify an individual basket of the basketgroup
232 # - closeandprint : close and print an closed basketgroup in pdf. called by clicking on "Close and print" button in closed basketgroups list
233 # - print : print a closed basketgroup. called by clicking on "Print" button in closed basketgroups list
234 # - ediprint : generate edi order messages for the baskets in the group
235 # - export : export in CSV a closed basketgroup. called by clicking on "Export" button in closed basketgroups list
236 # - delete : delete an open basketgroup. called by clicking on "Delete" button in open basketgroups list
237 # - reopen : reopen a closed basketgroup. called by clicking on "Reopen" button in closed basketgroup list
238 # - attachbasket : save a modified basketgroup, or creates a new basketgroup when a basket is closed. called from basket page
239 # - display : display the list of all basketgroups for a vendor
240 my $booksellerid = $input->param('booksellerid');
241 $template->param(booksellerid => $booksellerid);
242
243 if ( $op eq "add" ) {
244 #
245 # if no param('basketgroupid') is not defined, adds a new basketgroup
246 # else, edit (if it is open) or display (if it is close) the basketgroup basketgroupid
247 # the template will know if basketgroup must be displayed or edited, depending on the value of closed key
248 #
249     my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
250     my $basketgroupid = $input->param('basketgroupid');
251     my $billingplace;
252     my $deliveryplace;
253     my $freedeliveryplace;
254     if ( $basketgroupid ) {
255         # Get the selected baskets in the basketgroup to display them
256         my $selecteds = GetBasketsByBasketgroup($basketgroupid);
257         foreach my $basket(@{$selecteds}){
258             $basket->{total} = BasketTotal($basket->{basketno}, $bookseller);
259         }
260         $template->param(basketgroupid => $basketgroupid,
261                          selectedbaskets => $selecteds);
262
263         # Get general informations about the basket group to prefill the form
264         my $basketgroup = GetBasketgroup($basketgroupid);
265         $template->param(
266             name            => $basketgroup->{name},
267             deliverycomment => $basketgroup->{deliverycomment},
268             freedeliveryplace => $basketgroup->{freedeliveryplace},
269         );
270         $billingplace  = $basketgroup->{billingplace};
271         $deliveryplace = $basketgroup->{deliveryplace};
272         $freedeliveryplace = $basketgroup->{freedeliveryplace};
273         $template->param( closedbg => ($basketgroup ->{'closed'}) ? 1 : 0);
274     } else {
275         $template->param( closedbg => 0);
276     }
277     # determine default billing and delivery places depending on librarian homebranch and existing basketgroup data
278     my $patron = Koha::Patrons->find( $loggedinuser ); # FIXME Not needed if billingplace and deliveryplace are set
279     $billingplace  = $billingplace  || $patron->branchcode;
280     $deliveryplace = $deliveryplace || $patron->branchcode;
281
282     $template->param( billingplace => $billingplace );
283     $template->param( deliveryplace => $deliveryplace );
284     $template->param( booksellerid => $booksellerid );
285
286     # the template will display a unique basketgroup
287     $template->param(grouping => 1);
288     my $basketgroups = &GetBasketgroups($booksellerid);
289     my $baskets = &GetBasketsByBookseller($booksellerid);
290     displaybasketgroups($basketgroups, $bookseller, $baskets);
291 } elsif ($op eq 'mod_basket') {
292 #
293 # edit an individual basket contained in this basketgroup
294 #
295   my $basketno=$input->param('basketno');
296   my $basketgroupid=$input->param('basketgroupid');
297   ModBasket( { basketno => $basketno,
298                          basketgroupid => $basketgroupid } );
299   print $input->redirect("basket.pl?basketno=" . $basketno);
300 } elsif ( $op eq 'closeandprint') {
301 #
302 # close an open basketgroup and generates a pdf
303 #
304     my $basketgroupid = $input->param('basketgroupid');
305     CloseBasketgroup($basketgroupid);
306     printbasketgrouppdf($basketgroupid);
307     exit;
308 }elsif ($op eq 'print'){
309 #
310 # print a closed basketgroup
311 #
312     my $basketgroupid = $input->param('basketgroupid');
313     printbasketgrouppdf($basketgroupid);
314     exit;
315 }elsif ( $op eq "export" ) {
316 #
317 # export a closed basketgroup in csv
318 #
319     my $basketgroupid = $input->param('basketgroupid');
320     print $input->header(
321         -type       => 'text/csv',
322         -attachment => 'basketgroup' . $basketgroupid . '.csv',
323     );
324     print GetBasketGroupAsCSV( $basketgroupid, $input );
325     exit;
326 }elsif( $op eq "delete"){
327 #
328 # delete an closed basketgroup
329 #
330     my $basketgroupid = $input->param('basketgroupid');
331     DelBasketgroup($basketgroupid);
332     print $input->redirect('/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid.'&amp;listclosed=1');
333 }elsif ( $op eq 'reopen'){
334 #
335 # reopen a closed basketgroup
336 #
337     my $basketgroupid   = $input->param('basketgroupid');
338     my $booksellerid    = $input->param('booksellerid');
339     ReOpenBasketgroup($basketgroupid);
340     my $redirectpath = ((defined $input->param('mode'))&& ($input->param('mode') eq 'singlebg')) ?'/cgi-bin/koha/acqui/basketgroup.pl?op=add&amp;basketgroupid='.$basketgroupid.'&amp;booksellerid='.$booksellerid : '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' .$booksellerid.'&amp;listclosed=1';
341     print $input->redirect($redirectpath);
342 } elsif ( $op eq 'attachbasket') {
343 #
344 # save a modified basketgroup, or creates a new basketgroup when a basket is closed. called from basket page
345 #
346     # Getting parameters
347     my $basketgroup       = {};
348     my @baskets           = $input->multi_param('basket');
349     my $basketgroupid     = $input->param('basketgroupid');
350     my $basketgroupname   = $input->param('basketgroupname');
351     my $booksellerid      = $input->param('booksellerid');
352     my $billingplace      = $input->param('billingplace');
353     my $deliveryplace     = $input->param('deliveryplace');
354     my $freedeliveryplace = $input->param('freedeliveryplace');
355     my $deliverycomment   = $input->param('deliverycomment');
356     my $closedbg          = $input->param('closedbg') ? 1 : 0;
357     if ($basketgroupid) {
358     # If we have a basketgroupid we edit the basketgroup
359         $basketgroup = {
360               name              => $basketgroupname,
361               id                => $basketgroupid,
362               basketlist        => \@baskets,
363               billingplace      => $billingplace,
364               deliveryplace     => $deliveryplace,
365               freedeliveryplace => $freedeliveryplace,
366               deliverycomment   => $deliverycomment,
367               closed            => $closedbg,
368         };
369         ModBasketgroup($basketgroup);
370         if($closedbg){
371 # FIXME
372         }
373     }else{
374     # we create a new basketgroup (with a closed basket)
375         $basketgroup = {
376             name              => $basketgroupname,
377             booksellerid      => $booksellerid,
378             basketlist        => \@baskets,
379             billingplace      => $billingplace,
380             deliveryplace     => $deliveryplace,
381             freedeliveryplace => $freedeliveryplace,
382             deliverycomment   => $deliverycomment,
383             closed            => $closedbg,
384         };
385         $basketgroupid = NewBasketgroup($basketgroup);
386     }
387     my $redirectpath = ((defined $input->param('mode')) && ($input->param('mode') eq 'singlebg')) ?'/cgi-bin/koha/acqui/basketgroup.pl?op=add&amp;basketgroupid='.$basketgroupid.'&amp;booksellerid='.$booksellerid : '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid;
388     $redirectpath .=  "&amp;listclosed=1" if $closedbg ;
389     print $input->redirect($redirectpath );
390     
391 } elsif ( $op eq 'ediprint') {
392     my $basketgroupid = $input->param('basketgroupid');
393     generate_edifact_orders( $basketgroupid );
394     exit;
395 }else{
396 # no param : display the list of all basketgroups for a given vendor
397     my $basketgroups = &GetBasketgroups($booksellerid);
398     my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
399     my $baskets = &GetBasketsByBookseller($booksellerid);
400
401     displaybasketgroups($basketgroups, $bookseller, $baskets);
402 }
403 $template->param(listclosed => ((defined $input->param('listclosed')) && ($input->param('listclosed') eq '1'))? 1:0 );
404 #prolly won't use all these, maybe just use print, the rest can be done inside validate
405 output_html_with_http_headers $input, $cookie, $template->output;